Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i create a odd/even colored list, with modulus in Javascript?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 with document.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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading