Getting the href attribute of an image using Javascript

New in Javascript, really need help!

Now I have an image on an HTML page, for example:

<a class="p" href="http://www.abc.com"><img src="http://www.abc.com/logo.jpg" alt="" /></a>

And get the picture element:

var e.document.elementFromPoint(x,y);

When I clicked on the image, I can get the src attribute or offset attributes successfully:

e.src or e.offsetHeight

However, it returns NULL when I use:

return e.href;

So how can I get the correct href attribute (http://www.abc.com) ??

Thank,

Peak

+5
source share
3 answers

href is not the property of the image, but the element A.

You can use it using the .parentNodeimage property . since this is his direct parent.

+4
source

node img, a, parentNode:

return e.parentNode.href;
+3

The href attribute is available only for aand link. So you just need to get the parent node of the image:

var thea=e.parentNode;
if(thea.nodeName.toLowerCase()=="a"){ //If the tag is a hyperlink
    return thea.href;
}else{
    return ""; //Return an empty string if the image is not inside a hyperlink
}

Ad @ m

+1
source

All Articles