Ario
Ario

Reputation: 65

Check for an existence of a class from document selector

How to check for an existence of a class of the clicked element from document selector

Eg:

$(document).on("click",function(){
  // function to check the element class on which It's clicked
});

Upvotes: 0

Views: 51

Answers (2)

htxryan
htxryan

Reputation: 2961

Use jQuery's "hasClass()" method: http://api.jquery.com/hasClass/

if($(e.target).hasClass("myClass")){
     // Do something
}

Upvotes: 0

Joseph Silber
Joseph Silber

Reputation: 219938

$(document).on("click", function (e){
    console.log( e.target.className );
});

Here's the fiddle: http://jsfiddle.net/uQn8r/


If you want to check if the element that was clicked has a certain class, use this:

$(document).on("click", function (e){
    if ( $(e.target).hasClass('someClass') ) {
        // run some code...
    }
});

If you only want to run the function if the target element has a specific class, use this:

$(document).on('click', '.someClass', function (e){
    // run some code...
});

Upvotes: 1

Related Questions