开发者

Pushing child elements into a global array using jQuery

I am working on a script that will push each child element into a global array (for processing later on in my script) but for some reason its not actually pushing the element into the array.

Code:

var childElements=new Array();    
function getChil开发者_StackOverflowdren(elem){
            $(elem).children().each(function(index, value){
                childElements[index] = $(this);
            });
        }

Am I doing something wrong?


Since a jQuery object is an Array-like object, I'd probably just use that instead of creating an Array of individually wrapped objects.

var childElements=$(elem).children();

If you intend to add more elements, you can .push() always .add() new elements. This will also make sure you don't have duplicates.

var childElements= $();    
function getChildren(elem){
    childElements = childElements.add( $(elem).children() );
}


$.each($(elem).children(), function(index, value){ 
                childElements[index] = $(this); 
            });

Edit: Patrick is makes a valid point. If you simply want an array of child objects then a simple var childElements = $('selector').children(); should suffice. You don't need the function unless you want the values of that array to contain (a combination of) specific attributes from child elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜