jquery e.target.hasClass not working

JqueryEventsOnclickClassname

Jquery Problem Overview


I dynamically create a new div (with a "textbox" class and ID), and some other elements inside of it, and later on in my code I bind that div to the click event, and display the element clicked, like so:

$('#textbox_'+i).bind('click', function(event){
    alert(event.target.className);
}

This is fine, and it'll give me textbox as one of the classes displayed. But event.target.hasClass() doesn't seem to work. So, when I do the following, nothing happens:

$('#textbox_'+i).bind('click', function(event){
    if(event.target.hasClass('textbox')) { alert('got it!'); }
}

I tried it a few different ways and it appears to me that event.target.hasClass() just doesn't work. Is there another way to deal with events or am I doing something wrong?

Jquery Solutions


Solution 1 - Jquery

You're trying to use a jQuery method, hasClass(), on a standard DOM element. You need to convert the plain JS DOM element e.target to a jQuery object, like so:

$(event.target).hasClass('textbox')

And you end up with :

$('#textbox_'+i).on('click', function(event){
     if( $(event.target).hasClass('textbox')) alert('got it!');
});

Notice the use of on(), the proper closing of the click function, and you don't need curly brackets in your if statement if you're only executing a simple alert.

Solution 2 - Jquery

If you want to keep your JS DOM element plain without using jQuery...

event.target.classList.contains('textbox')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser961627View Question on Stackoverflow
Solution 1 - JqueryadeneoView Answer on Stackoverflow
Solution 2 - JqueryiarroyoView Answer on Stackoverflow