0

I am trying to check onclick if div have one of two different classes added to main div class and if there is no such - give back alert. Here is the example of all possible div's:

<div class="mainclass class1"></div>
<div class="mainclass class2"></div>
<div class="mainclass"></div>

If I am trying to check for class existence using JS something like,

$('.mainclass').click(function () {
    var check1 = $(this).hasClass('class1');
    var check2 = $(this).hasClass('class2');
    if(check1 == false || check2 == false)
                { 
                    alert("Hey, you are clicking empty field!")
                }
});

System will always give back alert even if I will click on first two div's. Is there any ways to make proper check of this using JS?

1
  • Its because the condition is fullfilled each time you click on any div :) Commented Apr 3, 2014 at 12:08

4 Answers 4

3

It's easier to apply these restrictions when selecting the object to be tracked:

$('.mainclass').not('.class1, .class2').click(function () {
  alert("Hey, you are clicking empty field!")
});

If these classes are indeed added/removed dynamically, again, state your intent directly:

$('.mainclass').click(function() {
    if ( $(this).is(':not(.class1, .class2)') ) { 
        alert("Hey, you are clicking empty field!");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Or: .not('.class1, .class2'). I give +1 but could not be what OP is looking for if classes are added/removed dynamically
1

You need AND && operator here instead of OR ||:

if(check1 == false && check2 == false)

Fiddle Demo

Comments

1

Just check like this

$('.mainclass').click(function () {
    var check1 = $(this).hasClass('class1');
    var check2 = $(this).hasClass('class2');
    if(!check1 && !check2 )
                { 
                    alert("Hey, you are clicking empty field!")
                }
});

another Way

$('.mainclass').click(function () {

    if(!$(this).hasClass('class1') && !$(this).hasClass('class2'))
         { 
            alert("Hey, you are clicking empty field!")
         }
 });

Comments

1

Change the operator to && not ||:

$('.mainclass').click(function () {
var check1 = $(this).hasClass('class1');
var check2 = $(this).hasClass('class2');
if(check1 == false && check2 == false)
            { 
                alert("Hey, you are clicking empty field!")
            }
});

Working Demo

Comments

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.