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