I have a div and it has several input elements in it... I'd like to iterate through each of those elements. Ideas?
Definition and Usage. The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.
The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
. each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.
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 () { /* ... */ });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With