iteration - How do I iterate through children elements of a div using jQuery?

ID : 10171

viewed : 29

Tags : jqueryiterationjquery

Top 5 Answer for iteration - How do I iterate through children elements of a div using jQuery?

vote vote

98

Use children() and each(), you can optionally pass a selector to children

$('#mydiv').children('input').each(function () {     alert(this.value); // "this" is the current element in the loop }); 

You could also just use the immediate child selector:

$('#mydiv > input').each(function () { /* ... */ }); 
vote vote

88

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {     console.log($(this)); //log every element found to console output }); 

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

vote vote

74

If you need to loop through child elements recursively:

function recursiveEach($element){     $element.children().each(function () {         var $currentElement = $(this);         // Show element         console.info($currentElement);         // Show events handlers of current element         console.info($currentElement.data('events'));         // Loop her children         recursiveEach($currentElement);     }); }  // Parent div recursiveEach($("#div"));    

NOTE: In this example I show the events handlers registered with an object.

vote vote

60

$('#myDiv').children().each( (index, element) => {     console.log(index);     // children's index     console.log(element);   // children's element  }); 

This iterates through all the children and their element with index value can be accessed separately using element and index respectively.

vote vote

52

It can be done this way as well:

$('input', '#div').each(function () {     console.log($(this)); //log every element found to console output }); 

Top 3 video Explaining iteration - How do I iterate through children elements of a div using jQuery?

Related QUESTION?