The jQuery text() method is used to set or return the text content of the selected elements.
To return content: When this method is used to return content, it returns the combined text content of all matched elements without the HTML markup.
To set content: When this method is used to set content, it overwrites the content of all matched elements.
Sometimes, this confusion is occurred because both of the methods are used to set or return the html content. But, the jQuery text() method is different from html() method.
Following is the main differences:
Syntax:
To return text content:
$(selector).text()
To set text content:
$(selector).text(content)
To set text content using a function:
$(selector).text(function(index,currentcontent))
Parameter | Description |
---|---|
Content | It is a mandatory parameter. It specifies the new text content for the selected elements. The special characters will be encoded in this parameter. |
Function (index,currentcontent) | It is an optional parameter. It specifies the function that returns the new text content for the selected elements.
|
Let's take an example to demonstrate the effect of jQuery text() method.
A simple example to return content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>text demo</title> <style> p { color: blue; margin: 8px; } b { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p><b>Hello! </b>rookienerd.com</p> <p></p> <script> var str = $( "p:first" ).text(); $( "p:last" ).html( str ); </script> </body> </html>
Output:
Hello! rookienerd.com
Hello! rookienerd.com
An example for set content:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p").text("Welcome to rookienerd.com!"); }); }); </script> </head> <body> <button>Click here to set text content for all p elements</button> <p>Hello Guys!</p> <p>Looking for online training....</p> </body> </html>
Output:
Hello Guys!
Looking for online training....