Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
     }
}
like image 320
joelson Avatar asked Jun 20 '11 15:06

joelson


People also ask

How do you link an image in JavaScript?

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.

What is JavaScript :; in href?

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.

Can an image have an href?

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.


2 Answers

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

like image 119
kapa Avatar answered Oct 18 '22 08:10

kapa


var a = document.getElementsByTagName("IMG");
for (var i=0, len=a.length; i<len; i++)
  alert (a[i].src); 
like image 32
rob Avatar answered Oct 18 '22 08:10

rob