Outputting element text via jQuery
The html and text
methods can be used not only to change the text of elements, but also to display it on the screen. Let's get an element
and display its text:
<p id="test">text</p>
alert($('#test').html());
If you try to get the text of not one element, but many, you will see only the content of the first element. Use the each method to get the text of all elements, it will be discussed in the following lessons.
In the example below we get all paragraphs with the class www:
<p class="www">text1</p>
<p class="www">text2</p>
<p class="www">text3</p>
Then we output the content using html, which will output only the text of the first paragraph from the received ones:
alert($('.www').html()); // will bring out 'text1'
You also need to be careful with the text method, in our case it will output the contents of all found elements:
alert($('.www').text()); // will bring out 'text1text2text3'