Search code examples
javascriptjqueryarrayschildren

Put images in an array - Javascript


At the moment, I have the code to put all my children of the "slides" class in an array in jQuery.

$('.slides').children().each(function (i) {
    var oImg = new Image();
    oImg.src = this.src;
    aImages.push(oImg);         
});

But now I heard that we have to use Javascript to create this. All my attempts to recode the snippet from jQuery to Javascript have failed. Does anybody know how to make it work?


Solution

  • Try this:

    // Get all the elements with class 'slides'
    var elements = document.getElementsByClassName('slides');
    
    // Loop through all the elements first...
    for (var j = 0; j < elements.length; j++) {
    
        // Get all the childNodes within each class 'slides'
        var children = elements[j].childNodes;
    
        // Loop through all the childrens
        for (var i = 0; i < children.length; i++) {
            var oImg = new Image();
            oImg.src = children[i].src;
            aImages.push(oImg);
        }
    }