jQuery text() Method

Last Updated:

jQuery text() Method

The jQuery text() method gets or sets the text content (innerText) of the selected elements.

The following points to be considered when using the jQuery text() method

  • When this method is used to get content, it gets the text content of all matched element.
  • When this method is used to set content, it will overwrite all matched elements.

Note: Unlike the html() method, text() can be used in both XML and HTML documents.

In the following example, we will get the text content inside the <div> tag.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery text() Method</h1> <div> <p>Click on the button and check your console.</p> <button>Click Me</button> </div> <script> $(document).ready(function(){ $("button").click(function(){ console.log($("div").text()); }); }); </script> </body> </html>

Syntax

// Get content $(selector).text(); // Set content $(selector).text(text); // Set content using a function $(selector).text(func)

Parameter Values

ValueExplanation
text Specifies a text to set as the content of each matched element.
func Specifies a function returning the text content to set.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
text()YesYesYesYesYesYesYesYesYesYesYesYesYes

Set Text Content

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery text() Method</h1> <button>Click Me</button> <p></p> <script> $(document).ready(function(){ $("button").click(function(){ $("p").text("This is <strong>Paragraph</strong>"); }); }); </script> </body> </html>

Set Text Content using Function

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery text() Method</h1> <button>Click Me</button> <p></p> <script> $(document).ready(function(){ $("button").click(function(){ $("p").text(function(){ var txt = "This is <strong>Paragraph</strong>"; return txt; }); }); }); </script> </body> </html>

Share this Page

Meet the Author