JavaScript changes img src attribute without jQuery

How to change src attribute of HTMLImageElement in JavaScript?

I need help converting 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'); } }; 
+10
source share
7 answers

Do you mean that 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 this:

 window.onresize = window.onload = function () { if (window.innerWidth > 1536) { var logo = document.getElementById('rm'); logo.src = "img/rm2.png"; } }; 

Note : you can also use element.setAttribute . BUT see this post more:
When to use setAttribute vs.attribute = in JavaScript?

+22
source

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'); } }; 
+1
source

I think this is just logo.src = "img/rm2.png" .

0
source
 var logo = document.getElementById('rm'); logo.setAttribute('src', 'img/rm2.png'); 
0
source

Since you say that you want to do this in different places of the program, I would create such a function:

 function ChangeImage(image_id,path) { document.images[image_id].src = path } 
0
source

So, if you want to check if the size changes, then change the verification code below.

 window.onresize = window.onload = function () { if (window.innerWidth < 768) { var logo = document.getElementById('changeLeft'); logo.src = "MobileImage.png"; }else{ var logo = document.getElementById('changeLeft'); logo.src = "DesktopImage.png"; } }; 

Adjust the window.innerWidth parameter to define breakpoints. Hope this helps.

0
source

Using eventListener and getAttribute in Javascript, how do I create a page whose images change when I click on the image?

0
source

Source: https://habr.com/ru/post/910867/


All Articles