How to iterate over children with for-loop

怎甘沉沦 提交于 2019-12-05 01:21:00

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

Wouldn't it be easier with this selector http://api.jquery.com/nth-child-selector/ ?

turpachull

You could use the each() function, and use "this" to get the current object. Then you can use the next() and prev() functions instead of i+1 and i-1 respectively. I haven't tested the code so it may or may not work; hopefully points in the right direction :)

jQuery.each($element.children(), function() {
{
    $(this).css('height', $(this).prev().height());
    $(this).css('width', $(this).next().width());
}

The each() function will work, take a look at this:

$('#something').children().each(function(index) { 

    $(this).css('width',  (parseInt($(this).css('width').replace('px', '')) + index) + "px");

    // to access the previous and next element:
    $(this).prev().css('width', '100px');
    $(this).next().css('width', '200px');

});

That will modify the width, adding the index as a pixel on each iteration - just to demo how to get the index.

Use .eq() to get the one at the specified index of the matched dom elements set.

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

and the another simple approach is to achieve this without for loop use .each()

jQuery.each($element.children(), function() {
{
    $(this).css('height', this.prev().height());
    $(this).css('width', this.next().width());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!