Reputation: 6625
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>
??
Upvotes: 5
Views: 1194
Reputation: 13461
You can get that using .get()
method
var arr = $("#t2").contents().get();
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();
});
Upvotes: 2
Reputation: 87073
var result = [];
$("#t2").contents().map(function(index, el) {
console.log(el);
if(el.nodeType == 3) {
result.push($.trim( $(el).text() ));
} else {
if(el.tagName.toLowerCase() == 'b') {
result.push('<b>' + el.innerHTML + '</b>');
} else if(el.tagName.toLowerCase() == 'p') {
result.push('<p>' + el.innerHTML + '</p>');
}
}
});
Upvotes: 1