tags:

views:

69

answers:

3

I have DOM elements I'd like to exclude from a .click function by adding a class "noEdit" the problem I'm having is some of these elements have multiple classes ie:

<td class="firstCol noEdit"> // <-- wont work
<td class="noEdit"> // <-- works fine

And the jQuery:

$('td').click( function(){
    if($(this).attr('class') != "noEdit"){
        alert('do the function');
    });

thoughts?

+5  A: 

If you query the class attribute with attr(), it simply returns the value as a single string. The condition then fails for your first <td> because your code will attempt to compare

"firstCol noEdit" != "noEdit"

Which returns true (since they're not equal) and causes your alert to display.

You'll want to look at the hasClass() function instead, which parses the class list for you and checks for the presence of the given class in the attribute:

$('td').click(function() {
    if (!$(this).hasClass("noEdit")) {
        alert('do the function');
    }
});
BoltClock
both great answers, I was more looking for this one though, as I can perform another function with my event targets that HAVE the class noEdit. Thanks :)
Jascha
@Jascha: that'd be three great answers; Dave just posted ;)
BoltClock
+4  A: 

How about using an attribute filter:

// != means 'not exactly matching', whereas *= means 'contains'
$('td[class!=noEdit]').click( function(){
    alert('do the function');
});
karim79
That seems much cleaner (the if condition is also no longer necessary since OP just wants to filter stuff depending on only the `noEdit` class). +1
BoltClock
@Boltclock - Heh, I realise that I left the `if` statement in the answer. How freaking stupid. (fixed now, but...)
karim79
hasClass may be faster though,.... It would be worthwhile to check the speed of this vs. that.
Elf King
Excellent. In this particular case I was looking more for boltclock's reply, but I'm upvoting for awesome tip. Thanks.
Jascha
+3  A: 

You can use jQuery's not() traversal to clean that up:

$('td').not('.noEdit').click(function() {
  alert('do the function');
});
Dave Ward
This is viable (and possibly) faster than the two above approaches, as it is using jQuery's list methods rather than the sizzle selector engine thingie. +1
karim79
@karim79: `not()` doesn't use Sizzle? That's interesting!
BoltClock
@Boltclock - I think that's the case (think != know) but I'm too lazy to check at this particular point in time :)
karim79
@karim79: I checked the source: `not()` seems to just call `pushStack()` with a `not` filter with the given selector.
BoltClock