jQuery Getters & Setter


jQuery Get or Set Contents and Values

Some jQuery methods can be used to either assign or read some value on a selection. A few of these methods are text()html()attr(), and val().

When these methods are called with no argument, it is referred to as a getters, because it gets (or reads) the value of the element. When these methods are called with a value as an argument, it’s referred to as a setter because it sets (or assigns) that value.

jQuery text() Method

The jQuery text() method is either used to get the combined text contents of the selected elements, including their descendants, or set the text contents of the selected elements.

Get Contents with text() Method

The following example will show you how to get the text contents of paragraphs:

Example

<script>
$(document).ready(function(){
    // Get combined text contents of all paragraphs
    $(".btn-one").click(function(){
        var str = $("p").text();
        alert(str);
    });
    
    // Get text contents of the first paragraph
    $(".btn-two").click(function(){
       var str = $("p:first").text();
       alert(str);
    });
});
</script>

Note: The jQuery text() retrieves the values of all the selected elements (i.e. combined text), whereas the other getters such as html()attr(), and val() returns the value only from the first element in the selection.

Set Contents with text() Method

The following example will show you how to set the text contents of a paragraph:

Example

<script>
$(document).ready(function(){
    // Set text contents of all paragraphs
    $(".btn-one").click(function(){
        $("p").text("This is demo text.");
    });
    
    // Set text contents of the first paragraph
    $(".btn-two").click(function(){
        $("p:first").text("This is another demo text.");
    });
});
</script>

Note: When the jQuery text()html()attr(), and val() methods are called with a value as an argument it sets that value to every matched element.


Leave a Reply

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