CSS Select first element found with attribute

This question already has an answer here:

I’ve tried :first-child :nth-of-type and a few other ways of selecting the first and last element found not based on the childs parent.

With CSS I want to select the first and last element found with a specific attribute regardless.

<div>
 <div></div>
 <div></div>
 <div data-select></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div data-select></div>
 <div></div>
 <div></div>
 <div data-select></div>
</div>

How would I select the first and last “data-select” element found regardless of its parent container?


solution

Since :nth-child only looks at the index of the children elements and :nth-of-type only looks at the type and index of the children elements, there is currently no direct way to select the first element with a given attribute.

Unfortunately, the closest thing you could do with pure CSS would be to select all the elements with that given attribute, and then override the applied styling for all subsequent elements with that attribute.

To do that, you could use the general sibling combinator, ~ along with an attribute selector.

div > div[data-select] {
  border-color: #f00;
}
div > div[data-select] ~ [data-select] {
  border-color: #000; /* Revert back to initial styling */
}

div > div {
  height: 1em;
  border: 2px solid #000;
  margin: 0.4em;
}
div > div[data-select] {
  border-color: #f00;
}
div > div[data-select] ~ [data-select] {
  border-color: #000; /* Revert back to initial styling */
}
<div>
  <div></div>
  <div></div>
  <div data-select>Select this</div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div data-select></div>
  <div></div>
  <div></div>
  <div data-select></div>
</div>