7

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?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Aaron
  • 2,702
  • 2
  • 27
  • 43

3 Answers3

7

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.

zzzzBov
  • 157,699
  • 47
  • 307
  • 349
  • Thanks! Interestingly, performance is worse when not scanning the tables, I guess because the :not selector takes some time as well. – Aaron Feb 11 '11 at 17:02
0
$('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;
});
Vadim
  • 17,547
  • 4
  • 36
  • 62
0

Use:

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

Check out this fiddle.

lsuarez
  • 4,853
  • 1
  • 25
  • 51