Say I have the following DOM element in my piece of code:
<div id="test">
<div id="t2">
Hi I am
<b>Gopi</b>
and am 20 years old.
<p id="div2">
<button onclick="alert('lol')">Check</button>
</p>
</div>
</div>
Suppose I wanted to traverse through the contents of div#t2.
$("#t2").children()
gives me the <b>
and <p>
tags.
So how should I access it to get the values as an array containing "Hi I am
", "<b>....</b>
", "and am 20 years old.
", "<p>.....</p>
??
Use the native DOM Node:
$('#t2')[0].childNodes
Gives you the array you want.
You'll probably want to trim the entries before using them using $.trim too since the actual text node contains all the whitespace in your HTML.
You can get that using .get()
method
var arr = $("#t2").contents().get();
Working Fiddle
If you check the fiddle you will find that .contents()
is returning an array consisting of
text
and html
elements like
[text1,html1,text2,html2,text3]
//Where
text1 == Hi I am
html1 == <b>Gopi</b>
text2 == and am 20 years old.
html2 == <p id="div2"><button onclick="alert('lol')">Check</button></p>
That perfectly makes sense, but where is the last text3
coming from.
There is another text nodes at the end of <p>
tag
<p id="div2">....</p> <-- Here, newline is
another text node(the last one)
So if you use .contents
keep that in mind.
To get trimmed data use $.map like
var arr = $("#t2").contents().map(function(){
if (this.nodeType == 3)
return $.trim(this.nodeValue) || null;
// this null to omit last textnode
else
return $('<div />').append(this).html();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With