Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  117] [ 7]  / answers: 1 / hits: 22958  / 12 Years ago, thu, march 22, 2012, 12:00:00

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.


More From » jquery

 Answers
25

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


[#86673] Wednesday, March 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesseh

Total Points: 579
Total Questions: 98
Total Answers: 99

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
;