Andrew Mackenzie
Andrew Mackenzie

Reputation: 5737

How select an element in CSS (using attribute) that is NOT a descendant of another element

After re-reading the CSS2.1 and CSS3 selector specs I suspect this is impossible, but you never know.

If I can select a p element, that is a decendent of other p element using the CSS decendant selector thus:

p p {};

Is there any way to negate the decendant selector, and still select on type, so I can select p elements, except those that are decendents of other p elements...

p & ( p ! p ) {...};

i.e. I want to select elements of type p, but NOT if they decend from other elements of type p.

BTW: I am using this in querySelector() and querySelectorAll(), where each one is selected by attributes not tag type, but I wanted to show the simplest example possible...

I tried this without success (syntax error!)

p:not(p p) {......}

Upvotes: 4

Views: 1130

Answers (3)

Quentin
Quentin

Reputation: 943193

You suspect correctly, it is impossible. :not(s) specifies that s must be a simple selector.

The nearest thing you can do is to apply a style to all p and then override it for p p.

Upvotes: 3

redShadow
redShadow

Reputation: 6777

While the :not(...) selector is only CSS3, I usually use this for CSS2 compatibility:

p { color: #abc; border: ... ; ... }
h1 > p { color: inherit; border: inherit; ... }

If your <p>s have a common ancestor, i.e. your html looks like this:

<body>
    <p> ... </p>
    <p>
        <p> ... </p>
        <p> ... </p>
    </p>
</body>

you can use the "direct-child" selector:

body > p { ... }

Or, of course, resetting all properties with something like:

p p { color: inherit; background: inherit; ... }

would work too..

Upvotes: 1

ldiqual
ldiqual

Reputation: 15365

*:not(h1) p {
  ...
}

This is called the negation pseudo-class, and you can find more informations about it here.

By the way, it is CSS3 so you can't use it with IE versions prior to 8.

Upvotes: 2

Related Questions