Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing child elements into a global array using jQuery

Tags:

arrays

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?

like image 272
dennismonsewicz Avatar asked Feb 10 '26 20:02

dennismonsewicz


1 Answers

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() );
}
like image 160
user113716 Avatar answered Feb 13 '26 15:02

user113716