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);
}
}
In JavaScript, get a reference to the image tag using the querySelector() method. Then, assign an image URL to the src attribute of the image element.
HREF JavaScript is a method to easily call a JavaScript function when a user clicks on a link on a website. If you've ever clicked a link and received a pop-up box, such as an alert dialog, then you've potentially seen this function in action.
Complete HTML/CSS Course 2022 To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With