How to Negate a Context

3.3k Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On
$('a').not(function() {
   return $(this).closest('table').length > 0;
});

or will likely be faster if they are always direct children of a <td> tag

$('a').not(function() {
   return $(this).parent('td').length > 0;
});
0
On

Use:

$("a").not("td a")

Check out this fiddle.