0

for a challenge, I am calling an the twitch TV API to get info and update my HTML.

Using a for loop, I succeeded to setAttributes for my divs and appendChilds. but when I want to update those childs, it is updating only the childs of the last div.

I need your help to update all my appended childs. Below is my code:

             // variables declarations to update the DOM
                var users = usersJson.data;
                var i;
                var usersIds = [];
                var channels = document.getElementById("all").children;
                console.log(channels);

                // pushing channels ids into an array for a later
                for (i = 0; i < users.length; i++) {
                    usersIds.push(users[i].id); 
                }

                var channelImg = document.createElement("img");
                var channelTitle = document.createElement("h3");

                for (var i = 0; i < channels.length; i++) {
                    channels[i].setAttribute("id", users[i].id);
                    channels[i].setAttribute("class", "channelInfo" + (i + 1) + " " + "channel" + (i + 1));

                    channels[i].appendChild(channelTitle);
                    channels[i].appendChild(channelImg).setAttribute("id", "img-holder" + (i + 1));

                    channelTitle.innerHTML = users[i].display_name;
                    channelImg.setAttribute("src", users[i].profile_image_url);

                }

https://jsfiddle.net/xpcz1r5k/1/

1 Answer 1

3

The creation of the elements needs to go in the for loop:

            for (var i = 0; i < channels.length; i++) {
                var channelImg = document.createElement("img");
                var channelTitle = document.createElement("h3");

                channels[i].setAttribute("id", users[i].id);
                channels[i].setAttribute("class", "channelInfo" + (i + 1) + " " + "channel" + (i + 1));

                channels[i].appendChild(channelTitle);
                channels[i].appendChild(channelImg).setAttribute("id", "img-holder" + (i + 1));

                channelTitle.innerHTML = users[i].display_name;
                channelImg.setAttribute("src", users[i].profile_image_url);

            }

When the creation is on the outside of the loop, appendChild only moves the element to the next parent. appendChild doesn't clone/duplicate the DOM elements. So you end up constantly updating the same DOM element and the last one ends up winning.

Sign up to request clarification or add additional context in comments.

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.