Refer to first occurrency of element with classname "foobar"?

Assume the following code:

<div class="foobar" ....>   // target
   <div class="foobar" ...>....</div>
</div>
<div class="foobar" .... >....</div>

Now I want to assign a new CSS rule to only the first element which has the class “foobar”. In the sample above the

with “target” as comment.
How can I address this?

[foobar]:first { color: red }

or

.foobar:first { color: red }

do not work

.foobar:first-of-type {color: red;}

2 Likes

That won’t work with the OPs nested code Dave as both the first two will get the first-of-type rule.:slight_smile:

You’d need to counter that second item.

e.g.

.foobar:first-of-type  {color: red;}
.foobar .foobar,
.foobar{color:blue;}

For the specific example, this works.
It works until you’ve got a non-foobar container that contains a foobar element.

This is beyond CSS’s scope to cover all scenarios.

Javascript will do it with document.getElementsByClassName("foobar")[0].style.color

1 Like