jQuery Tutorial Tutorials - jQuery .text() method

jQuery .text() method

The .text() method in jQuery 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.

jQuery .text() method Syntax

.text()
.text(text)
.text(function)
Parameter Type Description
text htmlString text content to be set.
function(index,oldHtml) Function function return the text content to set.index is the position of the element in the set and oldHtml is the old HTML value.

.text()

Get the text content of matched elements(including their descendants).

example

Find the text in the first paragraph (stripping out the html).
HTML

<p>Learn <strong>jQuery</strong></p>
<p>Learn JavaScript</p>

jQuery

$("p").text();

Result

Learn jQuery

.text(text)

Set the text content of each matched elements.

example

Add text to the paragraph (notice the paragraph tag is escaped).
HTML

<div id="container">
    <p>Learn JavaScript</p>
</div>

jQuery

$("#container").text('<p>more tutorials on lautturi.com</p>');

Try now

.text(function)

use function to set the text content

    $('p').text(function(index,oldText){
        return 'index:'+index+', old value:' +oldText;
    });

Try now

Date:2019-08-25 10:47:27 From:www.Lautturi.com author:Lautturi