Reputation: 1547
New to Javascript, really need some help!
Now I have an image in a HTML page, like this:
<a class="p" href="http://www.abc.com"><img src="http://www.abc.com/logo.jpg" alt="" /></a>
And get the image element by:
var e.document.elementFromPoint(x,y);
When I clicked on the image, I can get the src attribute or offset attributes successfully by:
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) ??
Thanks,
Peak
Upvotes: 5
Views: 4246
Reputation: 2049
The href atrribute is only available on a
and link
elements. 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
Upvotes: 1
Reputation: 30002
You can get the parent node of the img
, which is the a
using parentNode:
return e.parentNode.href;
Upvotes: 3
Reputation: 17375
The href is not a propery of the image but of the A element.
You can acces it by using the .parentNode
propery of the image. as it is its direct parent.
Upvotes: 4