开发者

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

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);
     }
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜