0

I'm trying to select all elements of a given class "class1" which don't have any ancestor in "class2". I thought the following selector would work:

:not(.class2) .class1

I am putting a space between the selectors because I want all descendants of elements not in class2 to be selected. But this didn't work, so I also tried changing the space to >. However this doesn't work quite right either.

I create a JSFiddle to demonstrate what I am expected versus what I actually see.

Update: It seems like the issue with using "space" is that this is literally selecting every element of class1 which has any element in its ancestry which is not in "class2", while the problem with ">" is that it only selects elements in which the parent is not "class2" without regard to whether further ancestors are in that class or not.

Update 2: After looking at the example by @DaniP it occurs to me that another way of looking at the problem is to subtract one set from another. So I tried .class1:not(.class2 .class1) but this apparently does not work because :not() doesn't accept complex selectors.

Michael
  • 9,060
  • 14
  • 61
  • 123
  • @Paran0a Ah, I was just trying to restate the title in other words, but you bring up a good point... I wasn't really thinking of this in terms of ancestors, are you saying that is the only way it could be done? – Michael Jun 01 '16 at 19:31
  • Isn't easier just do this https://jsfiddle.net/9okqkhq5/3/ ? – DaniP Jun 01 '16 at 19:34
  • `:not(.class2) .class1` selects all `.class1` which have some ancestor that doesn't match `.class2`. Not all `.class1` whose all ancestors don't match `.class2`. – Oriol Jun 01 '16 at 19:35
  • @DaniP That seems to work, but could I translate that to a querySelectorAll argument? (Yeah, I didn't mention that in my question, I didn't want to add what I thought would be an irrelevant detail at this point) – Michael Jun 01 '16 at 19:37
  • @DaniP in other words, I'm using CSS to try to prototype the selector I will need to specify which elements I am wanting to consider, but then I'm going to be using querySelectorAll to actually select them. – Michael Jun 01 '16 at 19:38
  • The way can be thinking on the opposite way ... selecting all `class1` inside `class2` instead of `class1` outside `class2` . So you will need to think again the actions for those elements . – DaniP Jun 01 '16 at 19:43
  • @DaniP Well I thought maybe `.class1:not(.class2 .class1)` would work, but that doesn't highlight *anything*. – Michael Jun 01 '16 at 20:41

0 Answers0