The code is messy but what I am trying to achieve is creating a class with the value of "cool" by using loops.
I started by putting each of the paragraphs in each of their own variable and then I placed them in a loop where I stated that I wanted each of them to have a classname of "cool", I also stated that I wanted this value i.e "cool" to display in the HTML just so that I can ensure that it is working, but is not going through and i would like to know what I am doing and/or you have a more efficient way of going about this.
var i;
var loop1 = document.getElementById("cool");
var loop2 = document.getElementById("cool1");
var loop3 = document.getElementById("cool2");
var loop4 = document.getElementById("cool3");
var loop5 = document.getElementById("cool4");
var loops = [loop1, loop2, loop3, loop4, loop5];
var loopsLng = loops.length;
for (i = 0; i > loopsLng; i++) {
document.getElementById(loops[i]).className = "cool";
var one = document.getElementById(loops[i]).getAttribute("class");
document.getElementById(loops[i]).innerHTML = one;
}
<p id="cool" style="margin-top:2rem; background-color:#b35900; padding:2rem; color:white;"></p>
<p id="cool1" style="margin-top:2rem; background-color:#b35900; 2rem; color:white;"></p>
<p id="cool2" style="margin-top:2rem; background-color:#b35900; padding:2rem; color:white;"></p>
<p id="cool3" style="margin-top:2rem; background-color:#b35900; padding:2rem; color:white;"></p>
<p id="cool4" style="margin-top:2rem; background-color:#b35900; padding:2rem; color:white;"></p>
2
Answers
The issue is in the loop itself
should be
i
variable in advance. In fact it’s better if you don’t, so that you don’t accidentally use it outside the loop.loops.length
into its own variable either.i > loopsLng
is inverted, it should bei < loopsLng
. This is the main problem.loops[i]
in a local variable so you don’t repeat it multiple times.for (const item of list)
. With this you don’t have to use indexes anymore.const
andlet
instead ofvar
, it’ll save you some headache with variable scoping in the future.loops
is not a very descriptive name for a list of elements. Tryelements
instead.