Pushing children 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 in my script), but for some reason it does not actually push the element into the array.

the code:

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

Am I doing something wrong?

+3
source share
2 answers

Since the jQuery object is an Array object, I would probably just use this instead of creating an array of individually wrapped objects.

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

If you intend to add more elements, you can .push()always have .add()new elements. It also ensures that you do not have duplicates.

var childElements= $();    
function getChildren(elem){
    childElements = childElements.add( $(elem).children() );
}
+3
source
$.each($(elem).children(), function(index, value){ 
                childElements[index] = $(this); 
            });

: . , var childElements = $('selector').children();. , , () .

+2

Source: https://habr.com/ru/post/1771993/


All Articles