Open In App

jQuery text() Method

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:

Example-1: Set text syntax.




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

Example 2: Return text syntax.




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

Example 3: Set text using a function.




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


Article Tags :