JQuery and If Statement do not match due to multiple classes

I have DOM elements that I would like to exclude from the .click function by adding the "noEdit" class that I have, some of these elements have several classes, for example:

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

And jQuery:

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

thoughts?

+5
source share
3 answers

If you request attribute classc attr(), it simply returns the value as a single string. The condition will fail for your first <td>, because your code will try to compare

"firstCol noEdit" != "noEdit"

Which returns true (since they are not equal) and causes your warning to be displayed.

hasClass(), :

$('td').click(function() {
    if (!$(this).hasClass("noEdit")) {
        alert('do the function');
    }
});
+6

:

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

You can use jQuery not () workaround to clear this:

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

All Articles