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

0 votes
48 views
Ethan Karla asked 28-Jul-2021 in Web Application by Ethan Karla

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

1 Answer

1 votes
Ravi Vishwakarma answered 29-Jul-2021 by Ravi Vishwakarma

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?