最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How can I get the href of all images on a page using JavaScript? - Stack Overflow

programmeradmin0浏览0评论

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.

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

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.

function checkimages() {
     var images = document.images;
     for (var i=0; i<images.length; i++){
        var img =images[i].src;
       alert(img);
     }
}
Share Improve this question edited Jun 2, 2016 at 4:15 Jules 1,7471 gold badge19 silver badges27 bronze badges asked Jun 20, 2011 at 15:58 joelsonjoelson 911 gold badge1 silver badge4 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

As @Kyle points out, an img does not have an href attribute, they only have src. Just guessing, but you might have a link (a) around your images, and its href stores the path to the big image (in case img is a thumbnail).

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

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

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

Probably you are looking for src attribute

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

评论列表(0)

  1. 暂无评论