0

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?

2
  • 1
    Technically that is JavaScript. I assume you mean that you aren't allowed to use jQuery. Commented Apr 23, 2013 at 8:21
  • Well yeah. It's mostly the first line of code that is causing issues Commented Apr 23, 2013 at 8:22

4 Answers 4

2

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

2 Comments

We're almost there, but apparently he can't find the variable children. The developer tools of Chrome tell me this: "Uncaught TypeError: Cannot read property "lenght" of undefined"
Great! That solved it. Stupid of myself that I didn't saw that the children variable wasn't a array
2

Something like:

var elements = document.getElementsByClassName("slides");
for(var i in elements){
  var childElements = elements[i].children;
  for(var j in childElements){
     var child = childElements[j];

     //your code here
  }
}

Comments

0

Try this:

    var elements = document.getElementsByClassName('slides');
    var myImages = elements.getElementsByTagName("img");

    for (var i = 0; i < myImages.length; i++) {
        var oImg = new Image();
        oImg.src = myImages[i].src;
        aImages.push(oImg);
    }

1 Comment

Stll an error: Uncaugght TypeError: Object #<NodeList> has no method 'getElementsByTagName'
0

Try

var aImages = [];

// get all elements with class slides
var slides = document.getElementsByClassName('slides');

// iterate through the slides array
for (var i = 0; i < slides.length; i++) {
    var slide = slides[0];

    // iterate through each child of slide
    for (var j = 0; i < slide.childNodes.length; i++) {
        var child = slide.childNodes[j];
        var oImg = new Image();
        oImg.src = this.src;
        aImages.push(oImg);
    }
}

Comments

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.