lundi 23 mars 2015

How to get href of anchor when the event.target is HTMLImageElement?


I want to get the href of an anchor element when it is clicked. I am using the following javascript code:



document.addEventListener('click', function (event)
{
event = event || window.event;
var el = event.target || event.srcElement;

if (el instanceof HTMLAnchorElement)
{
console.log(el.getAttribute('href'));
}
}, true);


This works perfectly for an embedded anchor such as this:



<div><p><a href='link'></a></p><div>


But it doesn't work when I am working with an anchor and an image:



<div><a href='link'><img></a></div>


The event.target is returning the image instead of the anchor. The javascript code can be amended with the following if case to get around this:



document.addEventListener('click', function (event)
{
event = event || window.event;
var el = event.target || event.srcElement;

if (el instanceof HTMLImageElement)
{
// Using parentNode to get the image element parent - the anchor element.
console.log(el.parentNode.getAttribute('href'));
}
else if (el instanceof HTMLAnchorElement)
{
console.log(el.getAttribute('href'));
}
}, true);


But this doesn't seem very elegant and I'm wondering if there is a better way.


!IMPORTANT! NOTE: Keep in mind, I have no access to an ID or class, or any other traditional identifier for that matter. All I know is that there will be an anchor clicked and I need to get its href.





Aucun commentaire:

Enregistrer un commentaire