Open In App

jQuery text() Method

Last Updated : 10 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This method is used to set or return the text content of the element. While setting the content, it overwrites the content of all the matched elements. The returned content of text method() is used to return the text content of all matched elements.

Syntax:

Return text syntax:

$(selector).text()

Set text syntax:

$(selector).text(content)

Set text using a function:

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

Property Values:

  • Content Required: It is used to set the new text content for the element.
  • Function(index, currentcontent): It is used to specify a function that will return the new text content for the selected elements.
    • index: It returns the index position of the element.
    • currentcontent: It returns the current content of element.

Example-1: Set text syntax.

html




<!DOCTYPE html>
<html>
 
<head>
    <title>
        jQuery text() Method
    </title>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").text("Jquery_text_method");
            });
        });
    </script>
</head>
 
<body>
    <h1>Geeks</h1>
    <button onclick="function()">
        Click me
    </button>
    <p>GeeksforGeeks</p>
    <p>Jquery</p>
 
</body>
 
</html>


Output:

jquery-36

Example 2: Return text syntax.

html




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert($("p").text());
            });
        });
    </script>
</head>
 
<body>
    <center>
        <h1>
            Geeks
        </h1>
        <button onclick="function()">
            Click me
        </button>
 
        <p>GeeksforGeeks</p>
        <p>Jquery</p>
 
    </center>
 
</body>
 
</html>


Output:

jquery-37

Example 3: Set text using a function.

html




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
 
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").text(function (n) {
                    return "Index No. of Element: " + n;
                });
            });
        });
    </script>
 
</head>
 
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
    <button onclick="function()">
        Click me
    </button>
 
    <p>GeeksforGeeks</p>
    <p>Jquery_textmethod()</p>
 
</body>
 
</html>


Output:

jquery-38



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads