.text()Returns: String
Description: Get the combined text contents of each element in the set of matched elements, including their descendants.
.html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.) Consider the following HTML:
1
2
3
4
5
6
7
|
|
$( "div.demo-container" ).text()
would produce the following result:
Demonstration Box list item 1 list item 2
.text()
method should not be used on form inputs or scripts. To set or get the text value of input
or textarea
elements, use the .val()
method. To get the value of a script element, use the .html()
method.
.text()
method returns the value of text and CDATA nodes as well as element nodes.
Example:
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
|
|
Demo:
.text( text )Returns: jQuery
Description: Set the content of each element in the set of matched elements to the specified text.
-
version added: 1.0.text( text )
-
textThe text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.
-
-
version added: 1.4.text( function )
-
functionA function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
-
.html()
method, .text()
can be used in both XML and HTML documents.
.createTextNode()
, does not interpret the string as HTML. Consider the following HTML:
1
2
3
4
5
6
7
|
|
$( "div.demo-container" ).text( "<p>This is a test.</p>" );
will produce the following DOM output:
1
2
3
|
|
1
|
|
.text()
method should not be used on input elements. For input field text, use the .val() method.
.text()
method allows us to set the text content by passing in a function.
1
2
3
|
|
<li>
elements, this example will produce the following DOM output:
1
2
3
4
5
|
|
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
|