Heres my element, i want to arrange the children inside it by looping through them.
<div id="animDummy1">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Heres how i imagine the code should look but children(), of course, doesn't return an array of the children
var children=$('#animDummy1').children();
for(var i=0;i<children.length;i++){
children[i].css('left',i*120+'px');
}
The question - can i get children array for use in a loop? I know i can attach a function for each of children to be executed on, but can i get that increasing "i" in there?
Thnx.
jQuery children() MethodThe 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.
Definition and UsageThe ("parent > child") selector selects all elements that are a direct child of the specified element.
jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
children()
returns a jQuery object of the children which resembles an array of DOM nodes. Your problem is inside the loop - when you access individual objects with []
you get back plain DOM nodes which don't have a css
method. Either use .eq(i)
or $(children[i])
.
Or just use the each() method, which lets you do the same without having to write a for loop by hand. Read the docs to find out how to get the index of the element inside the callback.
This is the correct way.
var children=$('#animDummy1').children(); children.each(function(idx, val){ $(this).css('left',idx*120+'px'); });
or actually this is better.
$('#animDummy1').children().each(function(idx, val){ $(this).css('left',idx*120+'px'); })
The other answers to use jQuery's children().each()
are likely helpful for most cases. However, if you do need an actual javascript Array, you can do the following:
var childrenArray = $('#animDummy1').children().toArray();
This would allow you have a real array for use in a loop or with other functions that require an array as a parameter.
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