简体   繁体   中英

How can you target a child element of an iterated object in JavaScript?

In this instance I simply want to target tables that have a thead tag.

I trying to concatenate or search using JavaScript or jQuery whichever is quicker.

eg thead = DT[i].children('thead');

 function go() { var i = 0, DT = document.getElementsByClassName('DT'); for (i; i < DT.length; ++i) { var x = DT[i]; if ($(x + ' thead').length) { //do stuff to this table } } } 
 <table class="DT" id="gv1"> <tbody> <tr> <th>th</th> </tr> <tr> <td>td</td> </tr> </tbody> </table> <table class="DT" id="gv2"> <thead> <tr> <th>thead</th> </tr> </thead> <tbody> <tr> <td>td</td> </tr> </tbody> </table> 

You don't need any loops, you can use jQuery's :has() selector to retrieve an element based on whether or not it contains a specified child, like this:

 function go() { $('.DT').has('thead').addClass('foo'); } go(); 
 .foo { border: 1px solid #C00; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="DT" id="gv1"> <tbody> <tr> <th>th</th> </tr> <tr> <td>td</td> </tr> </tbody> </table> <table class="DT" id="gv2"> <thead> <tr> <th>thead</th> </tr> </thead> <tbody> <tr> <td>td</td> </tr> </tbody> </table> 

You can use querySelector to check if the nested thead exists.

if (x.querySelector("thead")) {
  //do stuff to this table
}

Just so you know, you'd do this to accomplish what you were trying originally:

if ($(x).find("thead").length) {
  //do stuff to this table
}

This is just to show how you can perform DOM selection from a given context.

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