How do I iterate through children elements of a div using jQuery?
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.
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 () { /* ... */ });