Alex Pliutau
Alex Pliutau

Reputation: 21947

jQuery each div for first level


I have the next HTML.

<div id="id">
   <div>
      <div class="permissions">
      </div>
   </div>
</div>

And in jQuery I use loop.

$("#id div").each(function(){
   //do something
});

This loop run by all divs in #id. How make the same loop only by divs of the first level?
Thank you in advance. Sorry for my english.

Upvotes: 2

Views: 6068

Answers (1)

user113716
user113716

Reputation: 322542

By having a space between #id and div, you're using a descendant selector.

Instead, use a > child selector.

$("#id > div").each(function(){
   //do something
});

Now it will only target <div> elements that are a direct descendant (child) of #id.

It is the equivalent of using .children() instead of .find():

   // only direct descendant divs
$("#id").children("div").each(function() {
   //do something
});


   // all descendant divs
$("#id").find("div").each(function() {
   //do something
});

Upvotes: 12

Related Questions