Getting the Correct Element When Using - J Query

Your code is relying on the‖property of an event object, most likely in combination with event delegation, where one single event handler is bound to a container and it manages a variable number of descendant elements.In some cases, you don’t seem to be getting the expected behavior. is sometimes pointing to an element that is inside the one you expected.


The property refers to the element that got the event, that is, the specific element.
This means that if, for example, you have an image inside a link and you click the link, the will be the image, not the link.
So, how should you work around this? If you’re not working with event delegation,then using this (scope of the function) or event.currentTarget (since jQuery 1.3)should do. It will always point to the element that has the event handler bound.
If you’re indeed using event delegation, then you’ll need to find the parent element you were expecting.
Since jQuery 1.3, you can use closest().# As specified in its documentation, it will return the closest element, beginning with the current element and going up through the parents, that matches a certain selector.
If you’re using an older version of jQuery, you can simulate closest() with something like this:

This could be improved a little for performance, but this simple version should do for general purposes.
Here’s a small example of a very common situation using closest():

Discussion is one of the event object’s properties normalized by jQuery’s event system
(event.srcElement on IE).
So, how come an event is triggered on this target element and your event handler is called even when bound to an ancestor ? The answer is Event bubbling.*
Most standard DOM events do bubble.† This means that, after the event was triggered on the target, it will go up to its parent node and trigger the same event (with all its handlers).
This process will continue until either it reaches the document or event. stop Propagation() is called within an event handler.
Thanks to event bubbling, you don’t need to always bind event handlers to specific
elements; instead, you can bind to a common container once and handle them all from there. This is the principle of event delegation.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics