[Solved-5 Solutions] Getting the ID of the element that fired an event - javascript tutorial
Problem:
How to get the ID of the element that fired an event ?
Solution 1:
- The target property can be the element that listed for the event or a child of it.
- It is useful to compare
event.target
tothis
in order to determine if the event is being handled due to event bubbling. - This property is useful in event delegation, when events bubble.
Solution 2:
In jQuery event.target
always refers to the element that triggered the event, where 'event'
is the parameter passed to the function.
Solution 3:
To use a jQuery function, you must refer to it as '$(this)'
object.
Read Also
Event bubbling and capturingSolution 4:
You can use this code:
Solution 5:
$(event.target).id
is undefined$(event.target)[0].id
gives the id attribute.event.target.id
also gives the id attribute.this.id
gives the id attribute$(this).id
is undefined.
"id" is a DOM function so you have to be on the DOM element object to use it.