-1

I know there is a not operator in CSS that can be used at the root level. But can I apply CSS selector for child element not having a specific parent element ?

So I have a DOM structure as below;

<div>
<button value="applyCSSToThisBtn"/>
</div>
<div id="someId" class="someClass">
<button value="DONOTapplyCSSToThisBtn"/>
</div>

So basically I want to appy some CSS to the button (but only for that which does not have id="someId" as it's parent...Also button is not necessarily direct child)

copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 1
    `div:not(#someId) button {...` – j08691 Sep 24 '21 at 14:05
  • button is not a self-closing tag – VXp Sep 24 '21 at 14:08
  • Does this answer your question? [How to select an element's great-grandchild for CSS rules?](https://stackoverflow.com/questions/24268914/how-to-select-an-elements-great-grandchild-for-css-rules) – Heki Sep 24 '21 at 14:13
  • @Heki No, that's not a duplicate for this question, although I'm sure many do exist – j08691 Sep 24 '21 at 14:26
  • Yes, my question is I want to select only that element which does not have a specific parent/grandparent (so a NOT condition) – copenndthagen Sep 25 '21 at 11:30

4 Answers4

0
div:not([id]) button {
  color: red;
}

How about this? Applies style to all buttons that are children of a div without an id property.

Heki
  • 926
  • 2
  • 15
  • 34
0

You could use :not to point to your button that doesn't have an specified property

button{} //returns all buttons
    
button:not([id] {} //returns all buttons without id
Rogelio Monter
  • 1,084
  • 7
  • 18
0

Css has a pseudo class not.

To select all those buttons which are children (or grandchildren etc) of a div where that div does not have id someId you can do this:

div:not([id="someId"]) button {
  background: magenta;
}
<div>
  <button value="applyCSSToThisBtn">should be magenta</button>
</div>
<div id="someId" class="someClass">
  <button value="DONOTapplyCSSToThisBtn">should not be magenta</button>
</div>

Note: button is not self closing so this has been corrected in this snippet.

A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • For some reason, while this works for your example, it is not working for me....though I have a smilar structure as your example...and have button nested deeply down inside the container div. – copenndthagen Sep 27 '21 at 06:11
  • I think you'll need to give more code in your question that shows the actual structure because my example is the code you gave (except with the HTML errors corrected). Perhaps pass your actual code through a HTML/CSS validator too? – A Haworth Sep 27 '21 at 06:40
0

This selects all descendants of a parent that don't have the specified id. Run the code to see the result

div:not(#someId) button{background-color: yellow}
<div>
<button>Child1</button>
<section><button>Grandchild</button></section>
</div>

<div id="someId" class="someClass">
<button>Child2</button>
</div>
KarieJ
  • 41
  • 1
  • 2
  • 10