views:

173

answers:

4

i have a event i trigger on every link in my site.

but then i want it to NOT trigger on links i've got class='nofocus' on.

for example

 <a>link</a>
 <a class='nofocus'>register</a>

 $('a').live('click', function() {
     $('#searchbox').focus();
 }

how do i rewrite the $('a) so the second link wont trigger the event?

+1  A: 

Selector: $("a:not(.nofocus)") will select all links without the nofocus class. Use $("a:first"). http://docs.jquery.com/Selectors/first to just get the first one.

Jimmie Lin
+10  A: 

Theoretically, there are three options.

1. Using the “attribute not equal to” selector

The “attribute not equal to” selector matches elements that either don’t have the specified attribute or do have the specified attribute but not with a certain value.

$('a[class!=nofocus]')

This will only work as long as you don’t use multiple classes on your A elements in your markup, e.g. <a href="foo" class="nofocus bla bar baz">foo</a>.

See Selectors/attributeNotEqual in the jQuery docs for more information.

2. Using .not()

Another option is to select all the A elements first, then filter the results, removing elements with class="nofocus" from the result set.

$('a').not('.nofocus')

This is more flexible, because it allows the use of multiple classes on A elements.

Also, it’s slightly faster than using The Attribute Not Equal To Selector™ in Firefox, but slightly slower in Safari.

See Traversing/not in the jQuery docs for more information.

3. Using the :not() selector

The fastest (and shortest) option is to use the :not selector:

$('a:not(.nofocus)')

Also, my tests point out that this is by far the fastest method of the three — more than twice as fast as using the attribute not equal to selector!

Performance comparison of the three options

I created a jsPerf test case so you can test this yourself: http://jsperf.com/get-elements-without-specific-class.


TL;DR: Use $('a:not(.nofocus)').

Mathias Bynens
Shog9: Good point! I have now added an explanation to my answer.
Mathias Bynens
Good write-up, Mathias :-)
Shog9
Whoa! Was a good read. Of course, there's also $("a").filter(":not(.nofocus)"), but that's overkill already.
Jimmie Lin
@Jimmie Lin: I’ve added `$('a').filter(':not(.nofocus)')` to [the jsPerf test case](http://jsperf.com/get-elements-without-specific-class). You know, for the lulz. As expected, this is the slowest approach of them all :)
Mathias Bynens
+1  A: 
$('a:not(.nofocus)')

should do the job

http://docs.jquery.com/Selectors/not

peter p
+6  A: 

Try the :not() selector (docs):

$('a:not(.nofocus)').live('click', function() {
    $('#searchbox').focus();
}
jensgram