The problem is very simple: I can't find a way to select (only with css) the very first elem in page with a specific class.
For example with this HTML code I'd like to select the first element with class .elem:
.elem:nth-of-type(1) {
background-color: yellow;
}
<div class="wrapper">
<div class="elem">elem that I'd like to select</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
</div>
<div class="wrapper">
<div class="elem">Unfortunately, this elem is selected too</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
</div>
The current behavior is like the js' querySelectorAll function but the expected behavior is the one of querySelector:
document.querySelectorAll('.elem:nth-of-type(1)') // Current behavior is like this
document.querySelector('.elem:nth-of-type(1)') // Expected behavior is like this
Are there CSS tricks that can do what I want?
EDIT:
In the real case, I don't know the HTML code. The only thing I know is: "I need to select the very first .elem in the page with CSS"
.wrapper:first-child .elem:nth-of-type(1) {
background-color: yellow;
}
<div class="wrapper">
<div class="elem">elem that I'd like to select</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
</div>
<div class="wrapper">
<div class="elem">Unfortunately, this elem is selected too</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
<div class="elem">elem</div>
</div>
select with div select first div with wrapper class using pseudo:first-child
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With