简体   繁体   中英

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

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;
}

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM