I’m working on the Twitch API challenge and I’m trying to do something like this:
for (var i = 0; i < arrayLength; i++) {
document.getElementById(id).innerHTML = "<p class=i>Text</p>";
}
Example output:
Text //Paragraph with class = 0
Text //Paragraph with class = 1
(...)
Text //Paragraph with class = arrayLength - 1
Here’s the full code: http://codepen.io/tstusr/pen/WjRJvL . I want to do this so I can later have another ajax call which edits each paragraph to be online or offline.
Thanks a lot of for your answer. This for some reason makes every class “i-10”, is this because I’m using ajax? I fixed it by setting a variable outside the for loop and incrementing it for every iteration.
You are absolutely right about the problem, but there’s a better fix for it. Inside your for loop, create a variable that will store the value of i at the time that AJAX call is made.
for(var i = 0; i < users.length; i++) {
var counter = i; // counter will be the correct value
$.ajax(/*... stuff ... */)
}
Thanks a lot, I really hated having the variable outside the scope of the for loop just to serve as a counter.
Your solution is a lot more satisfying than my implementation