jQuery Api Tutorial For Text() Method

jQuery text () Method – how to use this method with selected text elements. Here you will learn how use text() method.

jQuery text() Method

The text () method is used for set or return the content of the selected HTML elements. When setting content, it overwrites the content of all matching elements. This returns the content of the text method () is used to return the text content of all matching elements.

Syntax

$(selector).text()  

This is used to return content.

$(selector).text(content)  

This is used to set content.

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

Text() method is used to set content by calling function.

Parameters of text() method

ParameterDescription
Content 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 of jQuery text() method

Let’s see the example 1 of text() method.

<!DOCTYPE html>  
<html>  
<title>Learn Jquery text Method</title>
<head>  
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
<script>  
$(document).ready(function(){  
    $("#btn_click").click(function(){  
        $("#para").text("Hello there, this is example");  
    });  
});  
</script>  
</head>  
<body>  
<button id="btn_click">Click here to change the content</button>  
<p id="para">This is a paragraph. When you click the button after that it will change.</p>  
</body>  
</html>  

Example 2 of text method

Let’s see example 2 of text () method, How to get the text inside an element.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Text Content Method</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
 
    $(".plain-text").click(function(){
        alert($(".plain").text());
    });
    
    $(".formatted-text").click(function(){
        alert($(".formatted").text());
    });
});
</script>
</head> 
<body>
    <p class="plain">This is plain text.</p>
    <p class="formatted">This <strong>is</strong> formatted <b> text </b> .</p>

    <button type="button" class="plain-text">Plain Text</button>
    <button type="button" class="formatted-text">Formatted Text</button>
</body>
</html>                            
Spread the love

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *