0

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.

2
  • 1
    You are only appending the last itemsList element to the list after the loop … Commented Aug 9, 2014 at 3:01
  • Yes, Thank you. I have solved it now. I know this is silly, but sorry :P . Just started out learning. Commented Aug 9, 2014 at 3:06

1 Answer 1

3

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

1 Comment

Thank you so much, This solved my issue. Accept your answer. Have a nice day.

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.