Getting Element Content in jQuery

jQuery .html() and .text() methods can be used to retrieve content of elements.
 

jQuery text() method

 
text() method returns the content from every element in the jQuery selection including any descendents.

Lets see the result of using .text() on the following HTML:
 

HTML Code

<div>
<p> First paragraph</p>
</div>
<div>
<p> Second paragraph</p>
</div>

jQuery Code

alert($('div').text());

Output

 
The alert shows a popup with following contents :
 
jquery text method

 

jQuery html() method

 
html() method retrieves HTML of first matched element.
 
So, if there is a set of matched elements, then only the first element in the matched set is returned, along with any of its descendants.

Lets see the result of using .html() on the previous HTML code :

 

jQuery Code

alert($('div').html());

Output

The alert shows a popup with following contents :
 
jquery html method
 
Note: If you want the value of every matched element you can use the .each() method.

 

Example with both .html() and .text() methods

 
Here is an example that displays the use of html() and text() methods for retrieving html content.
 

HTML Code

<div >
<p> First paragraph</p>
</div>

<div >
<p> Second paragraph</p>
</div>

Output of text() method :
<p id="outputtext"> </p>

Output of html() method :
<p id="outputhtml"> </p>

 

jQuery Code

var str1 = $('div').text();
$('#outputtext').text(str1);

var str2 = $('div').html();
$('#outputhtml').text(str2);


 

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags