Search code examples
javascriptjqueryhtmlcsspseudo-class

Simple mind-blowing thing; CSS selectors vs jQuery selectors


CSS selector :not() is not working and jQuery :not does. Consider this structure:

<div class="main">
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>
<div>
    <div class="doc-view">
        <ul>
            <li>One</li>
            <li>Two</li>
            <li>Three</li>
        </ul>
    </div>
</div>

And this simple CSS:

li:not(.doc-view li) {
    color:green;
}

And a little of jQuery here:

$('li:not(.doc-view li)').css('color','red');

As you can see, selectors are the same. But if you play with jsFiddle, you will see, that are not the same. jQuery selector targets elements, CSS does not.

http://jsfiddle.net/LL429/3/

EDIT:

The question is:

How to target all <li>s on the page, except those which are in .doc-view container?


Solution

  • This is because they mean different things. Let's start with the CSS.

    li:not(.doc-view li) 
    

    This means select all list items, but not those that have descendants that have the class doc-view with a list item descendant. Your code has none of those, plus only simple selectors are allow to be used with :not(), so the selector is invalid anyway.

    Now for the jQuery.

    $('li:not(.doc-view li)')
    

    This says select all list items, but do not include in that collection any elements with the class doc-view with a list item descendant. This works because it first select all list items, and then removes the matching group of elements that fit the :not(.doc-view li) selector.