Setting a different class for each iteration. Twitch API Challenge

Setting a different class for each iteration. Twitch API Challenge
0.0 0

#1

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.


#2

Change:

to:

note: a class name can not begin with a number

"<p  class='i-" + i + " '>Text</p>";

if Text is a variable you can do this:

"<p  class='i-" + i + " '> " + Text + "</p>";

#3

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.


#4

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 ... */)
}

#5

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 :slight_smile: