Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over children with for-loop

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.

like image 848
user1027167 Avatar asked Mar 22 '12 09:03

user1027167


People also ask

How do you iterate over a child's node?

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.

How do you iterate through children in jquery?

each( (index, element) => { console. log(index); // children's index console. log(element); // children's element }); This iterates through all the children and their element with index value can be accessed separately using element and index respectively.

Can you iterate over an object?

There are two methods to iterate over an object which are discussed below: Method 1: Using for…in loop: The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-Symbol iterable properties of an object.


1 Answers

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

like image 112
Strelok Avatar answered Sep 23 '22 16:09

Strelok