Thomas Sebastian
Thomas Sebastian

Reputation: 1612

Using a loop, but only one element is being added

I was working on some JavaScript and was trying to add things dynamically. Below is my code. My problem is that I am trying to add three "li" elements, attach "img" tags to it ans attaching the src dynamically. But it is attaching only the last image i.e in my code "bid_3" to all the "li". Help appreciated.

(function() {
    var bxSlider = document.createElement("ul"); //created ul
    bxSlider.setAttribute("class", "bxslider"); // gave a class name bxslider.

    for (i = 1; i < 4; i++) {
        var itemsList = document.createElement("li");
        var linkImages = document.createElement("img");
        linkImages.src = "images/bid_" + i + ".jpg";
        itemsList.appendChild(linkImages);
    }

    bxSlider.appendChild(itemsList);
    document.body.appendChild(bxSlider); //append everything to the body.

    var ulNum = document.getElementsByTagName("ul");
    alert(ulNum.length); // should return 1
    var liNum = document.getElementsByTagName("li");
    alert(liNum.length); // should return 3
    var imgNum = document.getElementsByTagName("img");
    alert(imgNum.length); //should return 3

    //call the slider.
    $(document).ready(function() {
        $('.bxslider').bxSlider();
    });

}());

PS:- I am not a JavaScript expert. Please forgive if my code is bad.

Upvotes: 0

Views: 72

Answers (1)

J. Titus
J. Titus

Reputation: 9690

You're only attaching itemsList after you've passed through the loop. Try this:

// Before loop stuff...
for (i = 1; i < 4; i++) {
    var itemsList = document.createElement("li");
    var linkImages = document.createElement("img");
    linkImages.src = "images/bid_" + i + ".jpg";
    itemsList.appendChild(linkImages);
    bxSlider.appendChild(itemsList);
}
// After loop stuff...

Upvotes: 3

Related Questions