:not(:last-of-type) not working for class

css, css-selectors

Solution

As mentioned, the reason is because `:last-of-type` matches an element that is the last sibling of its element type, in this case `div`. Since the last `div` isn't the last `.comment`, it doesn't match.

Unlike for the first element of a class, there is no way to use pure CSS to match the last element of a class, not even with an override. You should either use information about the existing structure to create a selector that will match the element you're looking for, such as:

.comment:not(:nth-last-child(2))

Or failing that, add an extra class name to the last `.comment` and exclude that, or otherwise alter the structure itself to accommodate your needs.

Problem

Why doesn't `:not(:last-of-type)` work in the following situation? How can I fix it? JSFiddle: http://jsfiddle.net/C23g6/589/ HTML: ``` <div class="comment">This is Red</div> <div class="hello">------------------</div> <div class="comment">This is Red</div> <div class="hello">------------------</div> <div class="comment">Shouldn't be Red</div> <div class="hello">------------------</div> ``` CSS: ``` .comment:not(:last-of-type) { color: red; } ```

Original source

Related problems