I have created a SVG icon. But when I click on it. It has chances that the return object is the line segement of the SVG reather than the svg element.
The clicked target is a POLYGON in the svg… How can this happen?
Advertisement
Answer
If you are trying to access the SVG element itself, you need the Event.currentTarget
property, not targetElement
or srcElement
. The srcElement
property is equivalent to the target
property, but is deprecated. The only targetElement
property I can find a reference to is defined on SVGAnimationElement
s, not on events.
As per MDN (emphasis mine):
The
currentTarget
read-only property of theEvent
interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed toEvent.target
, which identifies the element on which the event occurred and which may be its descendant.
Take a look at this snippet:
document.querySelector('svg').addEventListener('click', (e) => { console.log('Target: ' + e.target); console.log('Current target: ' + e.currentTarget); });
<svg xmlns="http://www.w3.org/2000/svg"> <rect width="100" height="100" fill="blue"/> <circle cx="50" cy="50" r="35" fill="red"/> </svg>