3

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?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304

1 Answers1

6

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>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • So what exactly does this select? div > div[data-select] ~ [data-select] How do I select the first and last using that? –  Apr 02 '15 at 22:29
  • 1
    @Shabbb: This makes use of an overriding rule. There are no CSS-based techniques to select the last element. If you're looking for a non-CSS-based solution, it depends on the application you're using that makes use of CSS selectors. See my answer to the duplicate question for some examples of the latter. – BoltClock Apr 03 '15 at 03:48