How to change the src
attribute of a HTMLImageElement
in JavaScript?
I need help to convert logo.attr('src','img/rm2.png')
to vanilla JavaScript.
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.attr('src','img/rm2.png');
}
};
You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.
Definition and UsageThe required src attribute specifies the URL of an image. Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified.
The <img> tag is used to embed an image in an HTML page. Images are not technically inserted into a web page; images are linked to web pages. The <img> tag creates a holding space for the referenced image. The <img> tag has two required attributes: src - Specifies the path to the image.
You mean you want to use pure javascript?
This should do it:
var logo = document.getElementById('rm');
logo.src = "img/rm2.png";
So your function should look like :
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.src = "img/rm2.png";
}
};
Note: You could also use element.setAttribute. BUT, see this post for more:
When to use setAttribute vs .attribute= in JavaScript?
try this...hope it works
window.onresize = window.onload = function () {
if (window.innerWidth > 1536) {
var logo = document.getElementById('rm');
logo.setAttribute('src','img/rm2.png');
}
};
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