tags:

views:

261

answers:

5

I have a simple jQuery selector that selects all links without a class of noValidate. It works great if I only have 1 class on an item however if I add a second class it will no longer find the class. How can I easily check if the class contains noValidate instead of is equal to it.

Current Selector

$("a[class!=noValidate]").click(function() {
    //Magic Happens
});

Works on:

<a href="#" class="noValidate">

Fails on

<a href="#" class="noValidate className2">
A: 

Can you do the opposite?

$("a:not[.noValidate]").click(...);
// or

$("a").click(function() {
    //Magic Happens
});
var noValidateEvents = $("a.noValidate").data("events");
$("a.noValidate").unbind('click', noValidateEvents.click[0]);
Daniel A. White
+2  A: 

Try:

$("a:not(a[class*=noValidate])").click(function() { });
eKek0
A: 

Change your selector to do this:

"a:not([class^='noValidate'])"

The ^= will match any element which has a class attribute that begins with "noValidate" and the not() wrapping it will negate the match.

If it is possible that the class "noValidate" could be in a different position inside the string try this:

"a:not([class*='noValidate'])"

which will match anywhere in the string. This last approach is more dangerous as you have a greater potential to match something else unintentionally.

Andrew Hare
+6  A: 

Any reason you are marking those links that shouldn't be validated as opposed to those that should? It would be much easier the second way, but if you need to stick to this then the you could do something like this:

$('a:not(.noValidate)').click(...);

This is using the not selector and only selecting links that don't have the class "noValidate". Internally jQuery has to get all the links in the page to see whether it has the class or not, which is not very efficient. Ideally, you would just give a class to links that should be validated, then you can do:

$('a.validate').click(...);

Much nicer, no? Much faster, too.

Paolo Bergantino
Nice explanation, including the performance note
Ed Schembor
+2  A: 

You could use the not selector:

$("a:not(.noValidate)").click(function() {
    //Magic Happens
});
TenebrousX