Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjlampstack
23,932 PointsIs there an nth-child for this?
it would be cool to be able to highlight every other list element to make it easier to read.
For example, :nth-child(even) or :nth-child(odd)
Also what if we wanted to select only the 3rd list element. Can we use something like :nth-child(4) ?
3 Answers
Stephan Olsen
6,650 PointsYou can use the querySelectorAll method to select all the elements by a css selector. This means that you can select every other element, or select the 3rd child of a list for example.
document.querySelectorAll("li:nth-child(even)")
andren
28,558 PointsEDIT: I just realized that I misunderstood this question, I though you were asking for help with CSS styling, not JavaScript selection. For that Stephan Olsen's answer is more apt. All of the selectors I reference in my post can be used with the querySelector
method he references.
:nth-child(even)
and :nth-child(odd)
are real, valid selectors. So a CSS rule like this:
li:nth-child(even) {
color: red;
}
Would make each even list-item element colored red.
As for selecting the third list-item specifically that would look like this:
li:nth-child(3) {
color: blue;
}
Here is a JSFiddle showing them off. JSFiddle is quite useful for quickly playing around with CSS selectors and the like. So if you are confused or curious about something you just learned, then I'd recommend quickly setting up some HTML and CSS on that site and playing around with it.
Brandon Tucker
1,915 PointsI added even and odd colors to my list making app by making changes in the CSS file and index file.
In index.html I simply added a class to the <ul> of items
and in the style.css I added
ul.items,
li:nth-child(even) {
background-color: lightpurple;
}
ul.items,
li:nth-child(odd) {
background-color: lightsteelblue;
}
The reason I opted to things this is way is to limit the code I had to add in javascript, also adding a class to the ul tag is my choice in future proofing my project in case I want to make another set of list items.
Caleb Kleveter
Treehouse Moderator 37,862 PointsCaleb Kleveter
Treehouse Moderator 37,862 PointsNot really sure what your question is. Can you expand a bit more?