user435216
user435216

Reputation: 305

Selecting Elements that Doesn't Contain a Specified Class with jQuery?

$("input").each(function() {
    if ($(this).hasClass('valid')) {
        // Do something
    }
});

The Code above determines if input has a specified class. However, how could I change the if statement to make it do something when input doesn't have a specified class?

Upvotes: 1

Views: 350

Answers (3)

Nick Craver
Nick Craver

Reputation: 630627

You can do it inside with a ! negation like this:

$("input").each(function() {
    if (!$(this).hasClass('valid')) {
        // Do something
    }
});

Or just use :not() when selecting those elements, like this:

$("input:not(.valid)").each(function() {
    // Do something
});

This means your original code can also be slimmer (for when it does have the class), like this:

$("input.valid").each(function() {
    // Do something
});

Upvotes: 3

John Hartsock
John Hartsock

Reputation: 86902

You can also use the :not selector

$("input:not(.valid)").each(function() {
   //Do Something
});

Upvotes: 2

lonesomeday
lonesomeday

Reputation: 238115

Use the negative operator !:

$("input").each(function() {
    if (!($(this).hasClass('valid'))) { // pass this statement if the valid class is not present
        // Do something
    }
});

Upvotes: 1

Related Questions