Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can select first child/last child of class in a mixed container?

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?

like image 825
Sami A. Avatar asked Oct 17 '13 00:10

Sami A.


1 Answers

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 (+).

like image 166
Jonathan Avatar answered Nov 02 '22 04:11

Jonathan