Jens Törnell
Jens Törnell

Reputation: 24748

Find first CSS class on page

I have a page full of elements. I simply just want to match the first element in my CSS selector.

I have tried sibling selector, first-child and first-of-type but they all only work in a structure where there are siblings. In my case I have different depths which makes it harder.

.match ~ .match {
  background:red;
}

.match:first-child {
  background: green;
}

.match:first-of-type {
  background: yellow;
}
<div>
  <ul>
    <li>List item</li>
  </ul>
  <div>
    <div class="match">Match - First match should be red</div>
  </div>
  <div class="match">Match</div>
  <button></button>
  <div>
    <div>
      <div class="match">Match</div>
    </div>
  </div>
</div>

It should find the first element with the class .match.

I will not accept answers like div > div > .match because then it does not find the element because we tell it where to look.

Upvotes: 0

Views: 70

Answers (1)

Skylar
Skylar

Reputation: 926

That is not possible with pure CSS. If the HTML is static, you can add an ID or another class, as Snake_py suggested. If you're okay with using a script, the document.querySelector method returns the first match of the selector, so you could do something like this: (see snippet)

document.querySelector('.match').classList.add('match-active')
.match-active {
  background:red;
}
<div>
  <ul>
    <li>List item</li>
  </ul>
  <div>
    <div class="match">Match - First match should be red</div>
  </div>
  <div class="match">Match</div>
  <button></button>
  <div>
    <div>
      <div class="match">Match</div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions