I'm currently learning web development with CSS, HTML and JavaScript.
This is my code:
const items = document.querySelectorAll('#players li'); console.log(items[0], items[1], items[2]);
<section id="players"> <h1>Test</h1> <ol> <li>Test1</li> <li>Test2</li> <li>Test3</li> </ol> </section>
What I want to do is to make a specific list item, let's say the third one to have a specific color. I can't figure out to how to use the style
property to set the CSS-property color
externally in my JavaScript file.
You could apply color
through the JavaScript style
property, eg:
const items = document.querySelectorAll('#players li'); if (items.length > 2) { items[2].style.color = "red"; }
<section id="players"> <h1>Test</h1> <ol> <li>Test1</li> <li>Test2</li> <li>Test3</li> </ol> </section>
Or you can achieve the same result just with the CSS nth-child
selector:
#players li:nth-child(3) { color: red; }
<section id="players"> <h1>Test</h1> <ol> <li>Test1</li> <li>Test2</li> <li>Test3</li> </ol> </section>
Iterate items
using forEach
and check the index
. Since the collection starts with 0
for third one you need to check if current index is 2
then use classList.add
to add a class and style it
const items = document.querySelectorAll('#players li'); items.forEach((item, index) => { if (index === 2) { item.classList.add('custom') } })
.custom { background: yellow; }
<section id="players"> <h1>Test</h1> <ol> <li>Test1</li> <li>Test2</li> <li>Test3</li> </ol> </section>
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.