jQuery text: Main Tips
- jQuery
.text()
returns the text inside the selected elements and their descendants. - You can also make jQuery change text inside each matched element to the specified content.
- Text is always defined in a string.
Using .text()
The .text()
method sets or returns the text inside the specified elements. Differently from .html(), jQuery .text()
is applicable to both XML and HTML documents.
In the example below, the function sets text to a <h1>
element:
When no parameters are defined, .text()
jQuery retrieves the text inside elements:
$(selector).text();
Follow this syntax to jQuery change text:
$(selector).text(content);
To make jQuery set text, a function
can also be added to retun the text needed:
$(selector).text(function);
In this case, the function
receives these arguments:
index
- the index of the currently selected element in the set of matched elements.currentContent
- the original text value of elements.
Tip: do not apply .text jQuery to form inputs or scripts. Use .val() instead.