Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get children array of an element in jquery

Tags:

jquery

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.

like image 719
Martin Avatar asked Feb 05 '12 18:02

Martin


People also ask

How to get children of an element using jQuery?

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.

What is parent and child in jQuery?

Definition and UsageThe ("parent > child") selector selects all elements that are a direct child of the specified element.

How use contains in jQuery?

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


3 Answers

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.

like image 179
Matti Virkkunen Avatar answered Sep 20 '22 11:09

Matti Virkkunen


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'); }) 
like image 23
thenetimp Avatar answered Sep 20 '22 11:09

thenetimp


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.

like image 43
Jason Avatar answered Sep 24 '22 11:09

Jason