Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery and If Statement Not Matching Because of Multiple Classes

Tags:

jquery

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?

like image 484
Howard Zoopaloopa Avatar asked Sep 12 '10 01:09

Howard Zoopaloopa


1 Answers

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');
    }
});
like image 80
BoltClock Avatar answered Sep 21 '22 18:09

BoltClock