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

4

5

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);
     }
}
Guyguyana answered 20/6, 2011 at 15:58 Comment(0)
S
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

Semantic answered 20/6, 2011 at 16:9 Comment(1)
I didn't think of that, but that's a very good possibility. +1Elephant
F
3
var a = document.getElementsByTagName("IMG");
for (var i=0, len=a.length; i<len; i++)
  alert (a[i].src); 
Fayola answered 20/6, 2011 at 16:8 Comment(0)
E
2

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

Elephant answered 20/6, 2011 at 16:0 Comment(2)
I know, and he is already doing that with the code he provided. I had to answer it because I couldn't just add a comment at the time.Elephant
then how return attribute anchor with images?Guyguyana
N
0

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);
     }
}
Neptunium answered 20/6, 2011 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.