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
4 Answers
Reset to default 10As @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);
}
}