Getting the href attribute of an image with Javascript

我的梦境 提交于 2021-01-27 05:31:28

问题


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


回答1:


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.




回答2:


You can get the parent node of the img, which is the a using parentNode:

return e.parentNode.href;



回答3:


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



来源:https://stackoverflow.com/questions/6452212/getting-the-href-attribute-of-an-image-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!