JQuery Text()

jQuery text() method is used to set or return the text content of the selected elements.

Below the syntax of jquery text() method

.text();

.text(content)

.text(function (index, currentcontent))

Parameters of jQuery text()
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.

Difference between jQuery text() and jQuery html()

jQuery.html() treats the string as HTML, jQuery.text() treats the content as text.

  • .text() can be used in both XML and HTML documents.
  • .html() is only for html documents.

Where to use:

  • use .html() to operate on containers having html elements..
  • use .text() to modify text of elements usually having separate open and closing tags.

Where not to use:

  • .text() method cannot be used on form inputs or scripts.

    • .val() for input or textarea elements.
    • .html() for value of a script element.
  • Picking up html content from .text() will convert the html tags into html entities.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery text()</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $("#button").click(function() {
     $("p").text("India is Great!")
  });
});
</script>
</head>
<body>
 <button style="margin:0 0 10px 0" class="btn" id="button">Change content of p element</button><br />
 <p>This is a paragraph.</p>
 </body>
</html>