jQuery text() examples

jQuery text() function is used to get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.

Example 1

Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>text demo</title>
    <style>
        p {
            color: blue;
            margin: 8px;
        }

        b {
            color: red;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p><b>Test</b> Paragraph.</p>
    <p></p>

    <script>
        var str = $("p").first().text();
        $("p").last().html(str);
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

Add text to the paragraph (notice the bold tag is escaped).
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>text demo</title>
    <style>
        p {
            color: blue;
            margin: 8px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>Test Paragraph.</p>

    <script>
        $("p").text("<b>Some</b> new text.");
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References


Comments