简体   繁体   中英

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

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

 });
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>');            
        }
   }
});

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM