Can I select the first and last children of a class in a div that has children of with various classes?
For example:
<div class="main">
<div class="red"></div>
<div class="red"></div>
<div class="red"></div>
<div class="black"></div>
<div class="black"></div>
<div class="black"></div>
<div class="green"></div>
<div class="green"></div>
<div class="green"></div>
</div>
I want to select first-child and last-child of .black
. Is that possible?
No, unfortunately not.
However, it is possible to select the first child of a certain class, by combining two selectors (example):
div.black:first-child,
div:not(.black) + div.black
The first selector selects a black div that's apparently the first child of it's parent. The second selector selects a black div that's preceded by a non-black div. Using these two rules, you can select the first black div.
For more information, see: :first-child
, :not
, and the adjacent sibling selector (+
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With