ajsie
ajsie

Reputation: 79676

jquery selector help

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?

Upvotes: 2

Views: 456

Answers (4)

Mathias Bynens
Mathias Bynens

Reputation: 149484

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)').

Upvotes: 11

jensgram
jensgram

Reputation: 31508

Try the :not() selector (docs):

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

Upvotes: 7

peter p
peter p

Reputation: 798

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

should do the job

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

Upvotes: 1

Jimmie Lin
Jimmie Lin

Reputation: 2215

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.

Upvotes: 1

Related Questions