jQuery text()

Introduction

Set text content for all <p> elements:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>/*ww  w  .ja  v a 2  s. c  o  m*/
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").text("Hello world!");
  });
});
</script>
</head>
<body>

<button>Set text content for all p elements</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

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

As getter, it returns the text content of all matched elements.

As setter, it overwrites the content of all matched elements.

To set or get the text + HTML markup of the selected elements, use the html() method.

Return text content:

$(selector).text()

Set text content:

$(selector).text(content)

Set text content using a function:

$(selector).text(function(index,current_content))
Parameter
Optional
Description
content

Required.

the new text content for the selected elements
Special characters will be encoded
function(index,current_content)


Optional.


sets a function that returns the new text content for the selected elements
index - the index position of the element in the set
current_content - current content of selected elements



PreviousNext

Related