Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first element but excluding those that are inside other element

I'm trying to select the first element in the body with class .box but excluding those inside the class .topbar.

I was using this approach :not(.topbar)>.box and is selecting all the elements .box excluding the one inside .topbar but I just want the first one.

I know that I can select it in an easier way but I'm wondering how could I do it that way...

Note: the number of elements are not fixed, so .topbar could exist or not...

Example:

<body>
    <div class="topbar">
        <div class="box">
            ...
        </div>
    </div>
    <div class="box"> <!-- Just want to select this one -->
        ...
    </div>
    <div class="box">
        ....
    </div>
</body>

Thanks!

like image 326
isramartinez Avatar asked Dec 03 '25 21:12

isramartinez


1 Answers

I think you can divide this up into two cases: 1) like in your example above, topbar is the first child and box is the second child 2) if topbar doesn't exist, then box is the first child

.topbar + .box, body > .box:first-child {background:red;}
like image 139
andi Avatar answered Dec 07 '25 18:12

andi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!