I'm trying to get the src of any image through plain JavaScript on mouseover.
// Retrieve image URL.
document.getElementsByTagName('img').onmouseover = getURL();
function getURL() {
var URL = this.getAttribute('src');
}
I can't bind any of these images to an ID and just getElementById. I have to get any image without modifying the DOM and without jQuery. Looks like getElementsByTagName gets you an array. How would I make this function work? Thanks.
.getElementsByTagName()
returns a nodelist which is array like . You have to add the event handler to each image or use event delegation .
var imgs = document.getElementsByTagName('img')
for(var i = 0; i < imgs.length; i++) {
imgs[i].onmouseover = getURL;
}
Since it returns an array, you must specify which array index to get. This should apply the onmouseover function to the first img tag that is found on the page.
// Retrieve image URL.
document.getElementsByTagName('img')[0].onmouseover = getURL;
function getURL() {
var URL = this.getAttribute('src');
}
And to apply this to all images on the page:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++)
{
images[i].onmouseover = getURL;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.