jQuery text() Method
The jQuery text() method serves as a means to access or modify the textual content of HTML elements. It's particularly useful for working with elements that contain only text, such as headings, paragraphs, or spans. Here are some examples illustrating the usage of the text() method:
Getting Text Content
Consider an HTML structure with a <p> element:
To retrieve the text content of this paragraph using jQuery:
Setting Text Content
To set or modify the text content of an element, you can use the text() method with an argument:
After executing this code, the content of the paragraph will change to "New text for the paragraph."
Working with Multiple Elements
When working with multiple elements, the text() method will get or set the text content of the first element in the selection. For instance:
In this example, the text content of both paragraphs will be updated to "Updated text."
jQuery Set and Get Contents with text() Method Examples
Set Contents with text() Method
Get Contents with text() Method
Changing this text to...
Difference between val() and text()
The val() method is versatile in that it retrieves the value of input elements regardless of their type, making it suitable for text inputs, checkboxes, radio buttons, and more. On the other hand, the text() method extracts the inner text (not HTML) from all selected elements, like paragraphs or headings. However, it's crucial to recognize that the text() method won't function as expected on input elements, as these elements don't possess inner text content like other standard HTML elements.
Conclusion
The text() method is especially suitable for handling plain text content, but it won't interpret or modify HTML tags within the content. If you need to work with HTML content, you can use the html() method instead.