Home > database >  How can I make the third item entered into an input box a different color? (JS, HTML, CSS)
How can I make the third item entered into an input box a different color? (JS, HTML, CSS)

Time:10-23

I have an input box that I can enter text into, press enter and it returns that text in a list. However, I want it to return every third element blue. How can I do this? Right now, I just have:

if(document.getElementById('item').value % 3 == 0) {
color: red;
}

CodePudding user response:

Using CSS:

#item:nth-child(3) {  
  color: #ccc;
}

Apply it to every third item:

#item:nth-child(3n) {  
  color: #ccc;
}

Consider using classes instead of ids.

CodePudding user response:

Assuming your list is a UL element you can filter all elements and extract only every third element and change it's color:

const every_nth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
every_nth([...document.getElementById("items").children], 3).map((e)=> e.style.color = 'blue');
li {
  color: red;
}
<ul id="items">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
  <li>g</li>
  <li>h</li>
  <li>i</li>
</ul>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related