Reputation: 305
$("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
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
Reputation: 86902
You can also use the :not selector
$("input:not(.valid)").each(function() {
//Do Something
});
Upvotes: 2
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