navigate through the child elements

Asked

Viewed 13,571 times

2

I would like to know how to make a loop to navigate through all the child elements?

Preferably code in Jquery, I believe it is something with next(), children(),find()....

2 answers

11

There are several ways to do this. You can use children or the find, optionally using some more specific selector. To traverse the elements, you can use the each.

// percorre todos os filhos
$(elem).children().each(function() {
    console.log($(this));
});

// percorre todos os filhos
$(elem).find("> *").each(function() {
    console.log($(this));
});

// percorre todos os li's filhos
$(elem).children("li").each(function() {
    console.log($(this));
});

// percorre todos os li's filhos
$(elem).find("> li").each(function() {
    console.log($(this));
});

I believe that using the children be the best option as it becomes clearer what you want to do and it will not go through all the elements below the parent element searching for those that close with the selector as the find ago.

  • you are using the selection this way > li, This is to indicate that you want the children of li and not more below, that’s it?

  • 1

    @Alexandrec.Caus That’s right. With the > I guarantee he will only take the elements immediately below the parent element.

2

You can use the Each() jquery

http://api.jquery.com/each/

<ul id="column1">
   <li rel="1">Info</li>
   <li rel="2">Info</li>
   <li rel="3">Info</li>
</ul>
<ul id="column2">
   <li rel="4">Info</li>
   <li rel="5">Info</li>
   <li rel="6">Info</li>
</ul>
<ul id="column3">
   <li rel="7">Info</li>
   <li rel="8">Info</li>
   <li rel="9">Info</li>
</ul>


$('ul li').each(function(i) {

});
  • whereas DOM element is an object, and I can traverse it with each, I can also traverse an array?

  • 1

    You can use JAVASCRIPT FOREACH. http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript

Browser other questions tagged

You are not signed in. Login or sign up in order to post.