Issue
Description
I'm currently trying to use the modulus operator in JavaScript, to target a specific HTML list and make it so the items in there that are odd has X color and those who are even has Y color.
function newFunction() {
var items = document.getElementById("oddEven");
var index = items.querySelectorAll("li");
console.log(index);
for (var i = 0; i < items.length; i++) {
console.log(i);
console.log(items[i]);
if (i % 2 == 1) {
document.getElementById("oddEven").style.color = "orange";
} else {
document.getElementById("oddEven").style.color = "blue";
}
}
}
newFunction();
<ul id="oddEven">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Errors None in JSlint, IDE VS CODE, Console.
Attempts I've searched around for similiar topics regarding modulus which there are a bunch of, but mostly all of them tend to be regarding background colors for completely different elements. Even when i've replicated others code and just edited out the targeted elements, i simply can't get it to work.
Question Is it that I'm using the for loop wrong here? Or is the modulus just completely off? I thought about the "if" and "else" document.getX, perhaps that is used wrong..
Is there someone who coud give a fresh eye of where my code is wrong, or just a hint..
Solution
A couple things...
- The
index
selector would have worked in the loop, but that wasn't even being used, so I've removed it. I've combined the two with method chaining. You could simplify further withdocument.querySelectorAll('#oddEven li')
. - You were setting the class on the list rather than the item. I'm setting it by index from the selector list.
function newFunction() {
var items = document.getElementById("oddEven").querySelectorAll("li");
for (var i = 0; i < items.length; i++) {
if (i % 2 == 1) {
items[i].style.color = "orange";
} else {
items[i].style.color = "blue";
}
}
}
newFunction();
<ul id="oddEven">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
Answered By - isherwood
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.