Shamoon
Shamoon

Reputation: 43521

How can I get the first matched element with a CSS selector that has different parents?

With the following HTML:

<div>
  <span class="something">...</span>
  <span class="something">...</span>
  <span class="something">...</span>
</div>
<article>
  <span class="something">...</span>
</article>

I want to find the first .something. How would I do this?

Upvotes: 2

Views: 199

Answers (2)

Unmitigated
Unmitigated

Reputation: 89284

You can't achieve this with only CSS. However, JavaScript's document.querySelector can be used to obtain the first element on the page matching a selector.

const first = document.querySelector('.something');
first.style.backgroundColor = "dodgerblue";
<div>
  <span class="something">...</span>
  <span class="something">...</span>
  <span class="something">...</span>
</div>
<article>
  <span class="something">...</span>
</article>

In order to affect pseudo elements, you can add a class to the element found with document.querySelector and add another style declaration in your CSS.

const first = document.querySelector('.something');
first.classList.add("first");
.something.first:after {
  content: "I'm the first one!";
  color: dodgerblue;
}
<div>
  <span class="something">...</span>
  <span class="something">...</span>
  <span class="something">...</span>
</div>
<article>
  <span class="something">...</span>
</article>

Upvotes: 2

Terminator-Barbapapa
Terminator-Barbapapa

Reputation: 3126

It's not possible to achieve this purely with CSS. It would have been possible if all the elements with the .something class would have had the same parent (see this solution). But since they are spread over multiple parents this won't work.

You can use jQuery for this which has a :first selector:

$( ".something:first" ).css( "color", "red" );
div, article {
  padding: 1em;
  border: 1px solid silver;
  margin-bottom: 1em;
  width: 100px;
}

span { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <span class="something">Something</span>
    <span class="something">Something</span>
    <span class="something">Something</span>
</div>
<article>
    <span class="something">Something</span>
</article>

Upvotes: 1

Related Questions