How to iterate over children with for-loop

user1027167 picture user1027167 · Mar 22, 2012 · Viewed 20.5k times · Source

I want to iterate over all childs of a jQuery's .children() return value, like this:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
    childs__.foo();

What do I have to write in the 3 line instead of __, to access the i-th child?

I want this becaus I want to access the (i-1)-th and (i+1)-th child in the loop, like this:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    childs<<i>>.css('height', childs<<i - 1>>.height());
    childs<<i>>.css('width', childs<<i + 1>>.width());
}

So I assume the each() function will not work.

Answer

Strelok picture Strelok · Mar 22, 2012

childs is a javascript array. So you access objects within the array by childs[indexOfElement]. In your case childs[i].

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
    childs[i].foo();

and

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    childs[i].css('height', childs[i-1].height());
    childs[i].css('width', childs[i+1].width());
}

BUT: Your code has an error. The element from the children collection is NOT a jQuery object. It's just an DOM element. So you have to wrap them in $(...) to use jQuery functions. So your code will become:

var childs = $element.children();        
for (var i = 1; i < childs.length - 1; i++)
{
    var thisElement = $(childs[i]);
    var next = $(childs[i+1]);
    var prev = $(childs[i-1]);
    thisElement.css('height', prev.height());
    thisElement.css('width', next.width());
}

PS. It should be named children. :)