Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a div and it has several input elements in it... I'd like to iterate through each of those elements. Ideas?

like image 890
Shamoon Avatar asked Jun 11 '10 16:06

Shamoon


People also ask

How do you get children of children in jQuery?

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.

How do you get the children of the $( this selector?

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.

How do you iterate through an array of objects in jQuery?

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.

How do you iterate in jQuery?

. 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.


2 Answers

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 () { /* ... */ }); 
like image 149
Andy E Avatar answered Oct 06 '22 00:10

Andy E


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.

like image 41
Liquinaut Avatar answered Oct 06 '22 01:10

Liquinaut