2

In CSS, can I select an element which doesn't contain another element?

For example:

<div>
    <p>ABC</p>
    <p>
        <q>123</q>
    </p>
    <p>ABC</p>
</div>

I want to set css for each p element, but not for the element which contains q.

Is this possible?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Patrick Keane
  • 663
  • 3
  • 19
  • 41

2 Answers2

2

If that is what your HTML looks like, you could use a method such as this...

div p {
   /* styles */
}

div p q {
  /* styles to *undo* previous styles, plus additional ones */
}
alex
  • 479,566
  • 201
  • 878
  • 984
  • You see, I have a margin set on the p elements which I dont want on the p > q element. It's also not convenient for me to change or remove the p element containing q. As commented above, I might be able to use the p:empty selector? – Patrick Keane Jun 13 '13 at 12:00
  • @PatrickKeane You could if they didn't have element or text nodes, but they do in your example. – alex Jun 13 '13 at 12:03
0

I have a margin set on the p elements which I dont want on the p > q element.

Unfortunately this isn't possible with CSS alone. You can however achieve this with JavaScript (the below example uses jQuery):

You can combine :not and :has:

$('p:not(:has(q))')

With this you can then modify the CSS using .css():

$('p:not(:has(q))').css({
    'margin': '5px'
});

Here is a JSFiddle demo.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • 2
    this hasn't been tagged with jquery - I made the same mistake with my answer – Pete Jun 13 '13 at 11:42
  • jQuery would be useful, but I'm developing for mobile and I'm leaving as much scripting work to the server side as possible. – Patrick Keane Jun 14 '13 at 08:20
  • @PatrickKeane if you're leaving the work to the server can you simply not add a separate class to elements with (or without) `q` children? – James Donnelly Jun 14 '13 at 08:25