javascriptcsssizzle

A javascript selector that matches on class, excluding others


I am trying to write a selector for querySelector that will include the divs of class "foo" but not "foo bar". I'm not using jQuery in this project.

<div class="foo">include me</div>
<div class="foo">and me</div>
<div class="foo bar">not me</div>

I have tried playing with :not() but am unsure of the correct syntax as this doesn't work for me

document.querySelectorAll('div.foo|*:not(.bar)');

Can anyone help?


Solution

  • It should be

    document.querySelectorAll('div.foo:not(.bar)');
    

    This will select all div elements having class .foo and not .foo with .bar

    Demo (Check the console for output)