html() / text()

조수경·2021년 11월 23일
0

HTML

목록 보기
74/96

$("body").html(); // body 태그 안의 모든 태그를 포함한 문장

$("body").text(); // body 태그안의 모든 문자만

$(“p").text(); //여러개인경우 모든 p태그의 문자만

$("p").html(); //p가 여러개인경우 첫번째 인거만 태그를 포함한 문장

//모든것을 대상 으로 실행시 - 반복루프를 사용


<body>
    <p>1<span>홍길동</span></p>
    <p>2<span>개나리</span></p>
    <p>3<span>진달래</span></p>  
</body>

$("p").length; -- p엘리먼트의 개수
반복문
$(요소선택).each(function(매개변수1, 매개변수2){…});
$.each(“요소선택, function(매개변수1, 매개변수2){…});
검색된 DOM요소의 개수만큼 지정된 fn함수를 호출한다

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel = "stylesheet" href = "../css/mystyle.css" type="text/css">
<script src="/jqpro/js/jquery-3.6.0.min.js" type="text/javascript"></script>

<script>
//$(document).ready(function(){
//})

$(function(){
	
	
	$('#bhtml').on('click', function(){
		str = $('body').html()/*가져와서 get */ 
		//str에는 태그가 포함되어 있다
		//$('#result1').html(str);/*set:result1을 str로 바꿔라*/
		//html출력시 str의 내용이 그대로 실행된다
		$('#result1').text(str);/*text로 찍어라 / text로 출력시 태그가 글자로 출력*/
		//str내용을 text로 출력시 태그가 글자로 출력
	})
	
	$('#btext').on('click', function(){
		str = $('body').text(); //str에는 태그가 포함되지 않는다
		$('#result2').html(str); //str에는 실행할 태그가 없다, text(str)로 실행한 결과와 같다
		//$('#result1').text(str);
	})
	
	$('#phtml').on('click', function(){
		str = $('p').html(); //첫번째 p태그만을 대상으로 하여 span태그 포함하여 내용 가져오기
		//$('#result3').html(str); // span태그가 실행되어 출력 한다
		$('#result3').text(str); // span태그가 실행되지 않고 글자로 출력된다
	})
	
	$('#ptext').on('click', function(){
		str = $('p').text(); // 전체 p를 대상으로 태그를 포함하지 않고 문자만 가져오기
		//$('#result4').html(str);
		$('#result4').text(str);
		
	})
	
	$('#html').on('click', function(){
		str = "";
		$.each($('p'), function(i){
			str += $('p').eq(i).html();
			$('#result5').html(str);
		})
		
		$('p').each(function(i){
			
		})
	})
	
})
</script>

<style>
span{
  background : yellow;
}
</style>
</head>
<body>

<div class = "box">
    html 버튼 클릭 - body안의 모든 태그를 포함한 내용을 가져온다
    text 버튼 클릭 - body안의 모든 내용만 태그 없이 가져온다
   <br>
  <button type = "button" id="bhtml">html</button>
  <button type = "button" id="btext">text</button>
  <div id = "result1"></div>
  <div id = "result2"></div>
</div>

<div class = "box">
    <p>1<span>홍길동</span></p>
    <p>2<span>개나리</span></p>
    <p>3<span>진달래</span></p>  
   <br>
  <button type = "button" id="phtml">html</button>
  <button type = "button" id="ptext">text</button>
  <button type = "button" id="html">html반복</button>
  <div id = "result3"></div>
  <div id = "result4"></div>
  <div id = "result5"></div>
</div>
</body>
</html>
profile
신입 개발자 입니다!!!

0개의 댓글