.text()
JQ Home <<
Manipulation <<
.text()
DOM insertion inside.
Description
The .text()
method is used to retrieve all text from the matched set including descendants, or set each element in the matched set to the specified text.
- The
.text()
method is available on both HTML and XML documents unlike the.html()
method which is only available on HTML documents. - The
.text()
method cannot be used on form inputs or scripts: - The
.text()
method calls the DOM method.createTextNode()
, which replaces special characters with their HTML entity equivalents ( eg. as > for > ), escaping the provided string as necessary so that it will render correctly in HTML. - When setting an element's content using the
.text( textString )
signature, existing content is replaced by the new content. - When setting an element's content using the
.text( function(index, text) )
signature, the existing element is cleared before the function is called. So use thetext
argument to reference the previous content.
Syntax
Signature | Description |
---|---|
.text() | Retrieve all text from the matched set including descendants. |
.text( textString ) | Set the text contents of each element within the matched set to the specified text. |
.text( function(index, text) ) | A function returning the text contents to set. |
Parameters
Parameter | Description | Type |
---|---|---|
htmlString | A string of raw HTML. | HTMLstring |
function(index, text) | A function.
|
Function |
Return
Retrieving - A String
object.
Setting - A jQuery
object including the updated text within the matched set.
.text()
Example
Manip. << Top
Retrieve all text from the matched set including descendants.
In the example below when we get the text contents of the table below which has an id of 'table1' and display them in an alert box.
Table Row 1, Table Data 1 | Table Row 1, Table Data 2 |
Table Row 2, Table Data 1 | Table Row 2, Table Data 2 |
$(function(){
$('#btn15').on('click', function() {
alert($('#table1').text());
});
});
.text( textString )
Example
Manip. << Top
Set the text contents of each element within the matched set to the specified text.
In the example below when we press the button we select all 'td' elements within the table with an id of 'testtable2'. We then change the text within each 'td' element.
Table Row 1, Table Data 1 | Table Row 1, Table Data 2 |
Table Row 2, Table Data 1 | Table Row 2, Table Data 2 |
$(function(){
$('#btn16').on('click', function() {
$('.testtable2 td').text('Table data changed');
});
});
.text( function(index, text) )
Example
Manip. << Top
A function returning the text contents to set.
In the example below when we press the button we add a new 'td' element to each table row.
? | ? |
? | ? |
$(function(){
$('#btn17').one('click', function() {
$('.testtable3 td').text( function(index, text) {
var newtext = text + '<td>' + index + '</td>';
return newtext;
});
});
});
Related Tutorials
jQuery Intermediate Tutorials - Lesson 2 - DOM Insertion, Inside