text()

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.

Difference between jQuery text() method and jQuery html() method

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:

  • The jQuery text() method is used to set or return html content without HTML markup while, html() method is used to set or return the innerHtml (text + HTML markup).
  • The jQuery text() method can be used in both XML and HTML document while jQuery html() method can't.

Syntax:

To return text content:

snippet
$(selector).text()

To set text content:

snippet
$(selector).text(content)

To set text content using a function:

snippet
$(selector).text(function(index,currentcontent))

Parameters of jQuery text() method

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.
  • Index: It provides the index position of the element in the set.
  • Currentcontent: It provides the current content of the selected elements.

Example of jQuery text() method

Let's take an example to demonstrate the effect of jQuery text() method.

A simple example to return content:

snippet
<!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

Another example of jQuery text() method

An example for set content:

snippet
<!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....

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +