Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing DOM elements by jQuery

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> ??

like image 992
gopi1410 Avatar asked Jun 04 '12 18:06

gopi1410


2 Answers

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.

like image 196
Paul Avatar answered Sep 24 '22 00:09

Paul


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();

 });
like image 37
Prasenjit Kumar Nag Avatar answered Sep 26 '22 00:09

Prasenjit Kumar Nag