jQuery API 살펴보기 text 메서드

기존의 자바스크립트에서 문서 객체의 textContent 속성과 관련된 jQuery 메서드이다.

html() 메서드와의 차이점은 text() 메서드는 HTML 태그를 인식하지 못한다.

또 html() 메서드는 요소 집합의 첫 번째 요소만 가지고 오는 것에 비해 text() 메서드는 선택자로 선택 한 모든 문서 객체의 글자를 출력한다.

사용법

html() 메서드와 달리 text() 메서드는 HTML 문서와 XML 문서에서도 사용이 가능하다.

메서드 형태

1
2
$('selector').text(value);
$('selector').text(function(index, text){});

예제

text() 메서드는 HTML 태그를 인식하지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p {
color: blue;
margin: 8px;
}
b {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p><b>Test</b> Paragraph.</p>
<p></p>

<script>
var str = $( "p:first" ).text();
$( "p:last" ).html( str );
</script>

</body>
</html>
1
2
3
4
5
6
7
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>

위와 같은 코드에 아래의 jQuery 메서드를 실행

1
$( "div.demo-container" ).text( "<p>This is a test.</p>" );

결과

1
2
3
<div class="demo-container">
&lt;p&gt;This is a test.&lt;/p&gt;
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>text demo</title>
<style>
p {
color: blue;
margin: 8px;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Test Paragraph.</p>

<script>
$( "p" ).text( "<b>Some</b> new text." );
</script>

</body>
</html>
Share