Search code examples
jquerycss-selectorsnegate

How to Negate a Context


I want to select elements, but not if one of their ancestor matches a certain selector.

For example, let's say I want to match all <a> nodes that are not descendants of a table.

I tried something like this:

$("a", ":not(table *)");

but that crashes my browser.

This one also hangs my browser:

jQuery("a", ":not(table td)");

The page queried is quite large, with lots of very large tables. So, I need something that performs well too. Any ideas?


Solution

  • The other answers are over-complicating things.

    $('a').not('table a');
    

    -or-

    $('a:not(table a)');
    

    The second parameter in the jQuery function is the context under which to search for an element, but selecting :not(table) will select every element that is not a table, which includes descendants of tables. Usually you want to use the context parameter when you have a specific document or element under which you would like to search.