3

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?

2 Answers 2

3

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() );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow this is very helpful! I have been looking for a way to clean up my code. Thanks!
2
$.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.

3 Comments

@dennismonsewicz - I'm a little confused. This is functionally equivalent to your original code.
@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 - 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.