如何使用 JavaScript 获取页面上所有图像的 href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6414060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:34:40  来源:igfitidea点击:

How can I get the href of all images on a page using JavaScript?

javascripthtmldom-traversal

提问by joelson

Is it possible for me to get the href of all images on a page using JavaScript? This code gives me the src for those images, but I want to return the href for them.

我可以使用 JavaScript 获取页面上所有图像的 href 吗?此代码为我提供了这些图像的 src,但我想为它们返回 href。

function?checkimages()?{
? ?? var?images?=?document.images;
? ?? for?(var?i=0;?i<images.length;?i++){
? ? ? ??var?img?=images[i].src;
       alert(img);
     }
}

回答by kapa

As @Kyle points out, an imgdoes not have an hrefattribute, they only have src. Just guessing, but you might have a link (a) around your images, and its hrefstores the path to the big image (in case imgis a thumbnail).

正如@Kyle 指出的那样, animg没有href属性,它们只有src. 只是猜测,但您的图像可能有一个链接 ( a),它href存储了大图像的路径(如果img是缩略图)。

In this situation, you could use:

在这种情况下,您可以使用:

function checkImages() {
     var images = document.images;
     for (var i = 0; i < images.length; i++){
        if (images[i].parentNode.tagName.toLowerCase() === 'a') {
           console.log(images[i].parentNode.href);
        }
     }
}

jsFiddle Demo

jsFiddle 演示

回答by rob

var a = document.getElementsByTagName("IMG");
for (var i=0, len=a.length; i<len; i++)
  alert (a[i].src); 

回答by Kyle Undefined

Images don't have an hrefattribute, that applies only to anchors (a).

图像没有href仅适用于锚点 ( a)的属性。

回答by Senad Me?kin

Probably you are looking for src attribute

可能您正在寻找 src 属性

function checkimages() {
     var images = document.getElementsByTagName('img');
     for (var i=0; i<images.length; i++){
        var img =images[i].getAttribute('src');
       alert(img);
     }
}