isramartinez
isramartinez

Reputation: 302

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!

Upvotes: 3

Views: 87

Answers (3)

Marc Audet
Marc Audet

Reputation: 46785

Here is a more robust way of doing it.

Consider a more generalized version of the original HTML snippet:

<div class="topbar">
    <div class="box">In the topbar...</div>
    <div class="box">In the topbar...</div>
</div>
<div>temp</div>
<div class="box">Just want to select this one...</div>
<div class="box">a second one....</div>
<div>temp</div>
<div class="box">a third one....</div>
<div>temp</div>
<div class="box">a third one....</div>

and apply the following CSS:

body > div.box
{
    background-color: beige;
}
body > div.box ~ div.box
{
    background-color: pink;
}

See demo at: http://jsfiddle.net/audetwebdesign/Rufcc/

The first rule selects all the div.box elements that are a child of body and applies a background color.

The second rule then selects all the div.box elements after the first one and then overwrites the background-color to some default value (could be transparent).

The main advantage of this approach is it can pick out the first div.box element regardless of how many other elements are before it.

Upvotes: 2

grimmus
grimmus

Reputation: 513

.topbar + .box { background:red; }

Upvotes: 1

andi
andi

Reputation: 6522

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;}

Upvotes: 3

Related Questions