The jQuery text() method is used to set or return the text content of selected elements. This is different from the jQuery html() method that we discussed in earlier. The jQuery html() method sets or returns content of selected elements with html tags while text() method returns or sets content without the html tags (just plain text).
When text() is used for returning content: When this method is used for returning content, you need not to pass anything to the method. For example, returning the text of all paragraphs can be done like this:
$("p").text();
Note: If there are multiple elements selected by the selector, then text() method returns the combined text content of all the elements in the same order in which they appeared on the page.
For example, if there are multiple paragraphs on a page and you use $(“p”).text(); then it will return text content of all the paragraphs combined (text of paragraph 1 + text of paragraph 2 + so on). We will see this in action in the following examples.
Syntax:
$(selector).text()
When text() is used for setting content of elements: When this method is used for setting the content, you need to pass the text inside the text() method like this:
$("p").text("Hi BeginnersBook.com Readers!");
This method overwrites content of all the matched elements with the content that is passed in the method as a parameter. For example, $(“p”).text(“Hi BeginnersBook.com Readers!”); will overwrite the content of all paragraphs with the message “Hi BeginnersBook.com Readers!”.
Syntax:
$(selector).text(content)
Example 1: jQuery text() method – Return text content
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("p").text());
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This example is shared on <b>BeginnersBook.com</b></p>
<button>Return the text content of all paragraphs</button>
</body>
</html>
Output:
Before button click:
After button click: As you can see the bold content of third paragraph doesn’t appear bold in returned content, this is because the text() doesn’t return html tags along with the content. If we would have used html() method here, the bold content of third paragraph would have returned bold.
Example 2: jQuery text() method – Set text content
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Welcome to BeginnersBook.com!");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the last paragraph.</p>
<button>Set text content for all paragraphs</button>
</body>
</html>
Output:
Before “set content” button click:
After “set content” button click: