Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the very first elem with class in the page [duplicate]

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"

like image 545
Victor Castro Avatar asked Dec 28 '25 09:12

Victor Castro


1 Answers

.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

like image 121
Mohammed Rabiulla RABI Avatar answered Dec 30 '25 23:12

Mohammed Rabiulla RABI