nth selector not getting the right first element.
I have a simple layout.
5 divs in a parent div.
All the divs are colored green alright?
However, i have some of the divs in the parent the class
.alternate
These alternate divs i wish to color the bachground based on even and odd.
Red for odd.
Yellow for even.
And it works.
However, if you take the alternate class off the first div, none of the other ones change colors.
I would expect from the selector it would select the second div as its the first(even) to now be red but it doesnt, it remains yellow.
Why is this?
Heres the script:
10 Replies
all alternate:

first div without alternate class, notice how the pattern didnt change, i would expect it to then be green, red, yellow, red yellow

nth-of-type looks at the tag type inside the parent, not at classes or other selectors
that second div is still the second div, the class is ignored
is there a way to make the class matter in this case?
MDN Web Docs
:nth-child() - CSS | MDN
The :nth-child() CSS pseudo-class matches elements based on the indexes of the elements in the child list of their parents. In other words, the :nth-child() selector selects child elements according to their position among all the sibling elements within a parent element.
that links to the specific heading, you can do
nth-child(2 of .alternate)
probably even nth-child(even of .alternate)?that does work 😄 ty!
np!
havent been here in a while, is there a thing we do to close a forum or make it solved or will time do that
You can add the solved tag if you want
It will just auto close after a few days of inactivity