What are the use of .text() method in JQuery explain with example?

Asked 28-Jul-2021
Viewed 183 times

1 Answer


1

The text method is used for fetching the inner text of selected elements but in html we can get or set text with html tag, it is optional to add tag name in text.

Syntax

$(selector).text()
 Return the text of selected elements
$(selector).text(content)
 Set text in selected elements
$(selector).text(function(index,currentcontent))
 Set text in selected elements by using function
<!DOCTYPE html>

<html>
<head>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
    <script>
        $(document).ready(function () {
            $('button').click(function () {
                $('.div1').html('<p>Hello !!! i am added in div tag by using the html tag</p>');
                $('.div1').text('<b>Hello !!! i am added in div tag by using the text tag</b>');
            });
        });
    </script>
    <style>
        .div1 {
            margin:10px;
            padding:10px;
            width:200px;
            height:200px;
            background-color:gray;
            color:white;
        }
    </style>
</head>
<body>
    <button>Click me</button>
    <div class='div1'>
    </div>
</body>
</html>

What are the use of .text() method in JQuery explain with example?