text() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:text

Description

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

When returning text, it returns the text content of all matched elements.

When setting content, it overwrites the content of all matched elements.

Syntax

Parameter RequireDescription
contentRequired. new text content for the selected elements
function(index,currentcontent) Optional. a function that returns the new text content for the selected elements
  • index - the index position of the element in the set
  • currentcontent - current content of selected elements

The following code shows how to set text content for all <p> elements:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").text("Hello world!");
    });//from   w  w w .jav  a 2s  .co m
});
</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>

Related Tutorials