61

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?

Hafenkranich
  • 1,696
  • 18
  • 32
user961627
  • 12,379
  • 42
  • 136
  • 210

2 Answers2

106

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Wow! okay that was simple! Maybe this is a little off topic, but what's the difference between $(event.target) and event.target? The former works with hasClass, but not when I try to alert .className. – user961627 Aug 28 '12 at 08:04
  • 5
    hasClass is a jQuery function, .className is plain javascript – anderssonola Aug 28 '12 at 08:05
  • 2
    The first one is wrapped in jQuery, so it's a jQuery object and can be used with jQuery methods. The second is a plain javascript object returned in the functions `event` and can be used with plain javascript methods but not jQuery methods. – adeneo Aug 28 '12 at 08:05
  • 1
    I needed to stop propogation on a .live listener; so I used the above tip and got `if(!$(e.target).hasClass("seeDetails")) return false;` and it worked great. Thanks! – Thomas Oct 10 '13 at 04:24
  • Great solution. However, I'm getting this error when the document loads: `ReferenceError: event is not defined`. Any ideas? – Ralph David Abernathy Aug 30 '15 at 15:10
  • @RalphDavidAbernathy - did you remember the argument, as in `...function(event) {` – adeneo Aug 30 '15 at 16:13
  • I really like it when SO folks provide the "what you did" and then explain what you need to do instead. Nice job adeneo! – HPWD Oct 10 '16 at 14:46
51

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

event.target.classList.contains('textbox')
iarroyo
  • 2,354
  • 24
  • 23