5

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?

3 Answers 3

7

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');
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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: that'd be three great answers; Dave just posted ;)
4

How about using an attribute filter:

// != means 'not exactly matching', whereas *= means 'contains'
$('td[class!=noEdit]').click( function(){
    alert('do the function');
});

4 Comments

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 - Heh, I realise that I left the if statement in the answer. How freaking stupid. (fixed now, but...)
hasClass may be faster though,.... It would be worthwhile to check the speed of this vs. that.
Excellent. In this particular case I was looking more for boltclock's reply, but I'm upvoting for awesome tip. Thanks.
3

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

$('td').not('.noEdit').click(function() {
  alert('do the function');
});

4 Comments

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: not() doesn't use Sizzle? That's interesting!
@Boltclock - I think that's the case (think != know) but I'm too lazy to check at this particular point in time :)
@karim79: I checked the source: not() seems to just call pushStack() with a not filter with the given selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.