$(this) and this aren’t the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id property exists on the element, but not the jQuery object. As such, you have a few options:
-
Access the property on the element directly:
this.id -
Access it from the jQuery object:
$(this).attr("id") -
Pull the object out of jQuery:
$(this).get(0).id; // Or $(this)[0].id -
Get the
idfrom theeventobject:When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items:
currentTargetandtarget.Using
target, you can get theidof the element that raised the event.currentTargetwould simply tell you which element the event is currently bubbling through. These are not always the same.$("#button").on("click", function(e){ console.log( e.target.id ) });
Of all of these, the best option is to just access it directly from this itself, unless you’re engaged in a series of nested events, then it might be best to use the event object of each nested event (give them all unique names) to reference elements in higher or lower scopes.