tags:

views:

36

answers:

2

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?

Thanks! Dennis

Edit (working code):

var childElements = $();    
function getChildren(elem){
        childElements = childElements.add( $(elem).children() );
        console.log(childElements);
    }
+1  A: 
$.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.

Saul
Sweet! Thanks! I added in my working code above
dennismonsewicz
@dennismonsewicz - I'm a little confused. This is functionally equivalent to your original code.
patrick dw
@patrick - how would you simply my code? Having to loop through each array is the only way I could come up with a way of doing it
dennismonsewicz
@dennismonsewicz - Depends on what you ultimately want to accomplish. I certainly wouldn't see much use in creating an Array with individual jQuery objects, when a jQuery object is (effectively) an Array of elements. I'll add an answer.
patrick dw
+1  A: 

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() );
}
patrick dw
Wow this is very helpful! I have been looking for a way to clean up my code. Thanks!
dennismonsewicz