Using `:first-of-type` with data attribute values?
Should I be able to use a CSS selector like
[data-progress="pending"]:first-of-type
?
Background: I have a series of elements, each with a [data-progress='pending'|'done']
attribute. All elements start as pending
and change to done
when they finish (they complete in order). I want to set a darker background color for all of them to start. The first with a pending
state I want to give a white background. When that one changes to done
it would turn green and the next element would turn white. The result I'm getting is as if :first-of-type
only recognizes the [data-progress]
attribute itself and not the value. Is this the way it works or do I need to be looking for a bug in my code somewhere. I've Googled and MDN'ed and haven't been able to find an answer.
Code Example: This is a simplified example of what I'm doing:
So, the question is, should :first-of-type
work with data attribute values like this?
Thanks!6 Replies
you've misunderstood what that pseudo-class does
it selects the first elements of a certain "type"
https://developer.mozilla.org/en-US/docs/Web/CSS/:first-of-type
as you can see in the examples, if onyl selects the first of a specific tag for that level
in this case, it will always targed the first
<div>
to do what you want, you need the :nth-child
with the of
variant:
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child#the_of_selector_syntax
so, in this case:
https://jsfiddle.net/dy91ouLj/ <-- notice how the 2nd one is red
Edit fiddle - JSFiddle - Code Playground
JSFiddle - Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle.
Just sat down to supper, I’ll take a look at the Fiddle after.
Thanks for the explanation. What you said makes sense and I was suspecting as much. However, I realized that I used classes on the divs rather than the data attributes which is what I meant to do. (Oops). I have changed the original code to what was intended. Does this change your answer at all? My guess is ‘no’, but figured I should ask. 😉
no, not at all
you're just misusing classes, but that's fine
I was afraid of that. Thanks for the clarification.
you're welcome