dennismonsewicz
dennismonsewicz

Reputation: 25542

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 getChildren(elem){
            $(elem).children().each(function(index, value){
                childElements[index] = $(this);
            });
        }

Am I doing something wrong?

Upvotes: 3

Views: 4636

Answers (2)

Saul
Saul

Reputation: 18071

$.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.

Upvotes: 2

user113716
user113716

Reputation: 322562

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() );
}

Upvotes: 3

Related Questions