text() method in jQuery

text() in jQuery

Using this method we can retrieve all the text contents of each element including their descendants, or set the text contents of the matched elements.

This method cannot be used on form inputs or scripts.

Syntax 1 - Get the combined text contents of each element in the set of matched elements, including their descendants.

$(selector).text()

Syntax 2 - Set the content of each element in the set of matched elements to the specified text.

$(selector).text(text)

  • text - The text to set as the content of each matched element.
Syntax 3 - A function returning the value to set

$(selector).text(function(index, currentTextString))

  • index - Index position of the element in the set.
  • currentTextString - The old text value.

text() method convert like below

< to &lt;

> to &gt;


Example 1 - get text

Try Yourself

Example 2 - set text

Try Yourself

Example 3 - get old text and set new text

Try Yourself

Example 4 - Execution steps

Try Yourself

Example 5 - Get drop down text and selected text

Try Yourself

Difference between html() and text()

Using text() method it retrieves only the text from an element, but using html() method both the text as well as the HTML markup can be retrieved from the element.

Example

Try Yourself