Accessing DOM Elements Using jQuery
Let's 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 go through the contents of div # t2.
$("#t2").children()gives tags <b>and <p>.
So , how should I access it in order to get values in the form of an array containing " Hi I am", " <b>....</b>", " and am 20 years old.", " <p>.....</p> ?
+5
3 answers
var arr = $("#t2").contents().get();
, , .contents() ,
text html ,
[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>
, text3.
<p>
<p id="div2">....</p> <-- Here, newline is
another text node(the last one)
, .contents, .
, $.map,
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();
});
+2
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>');
}
}
});
+1