18

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');
    }
};
Axel
  • 3,331
  • 11
  • 35
  • 58
technopeasant
  • 7,809
  • 31
  • 91
  • 149

6 Answers6

33

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?

Community
  • 1
  • 1
gideon
  • 19,329
  • 11
  • 72
  • 113
  • 5
    dang it, beat me by 8 seconds :) – dbrin Mar 16 '12 at 04:08
  • :) Yea the JS/JQuery questions really have too many people fighting to [shoot an answer.](http://meta.stackexchange.com/questions/9731/fastest-gun-in-the-west-problem) – gideon Mar 16 '12 at 04:12
1

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');
    }
};
Tejasva Dhyani
  • 1,342
  • 1
  • 10
  • 19
0

So if you want to check if the size has changes and then changes back check code bellow.

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 window.innerWidth to decide on your break points. Hope that helps.

Sabba Keynejad
  • 7,895
  • 2
  • 26
  • 22
0

I think it's just logo.src = "img/rm2.png".

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
dbrin
  • 15,525
  • 4
  • 56
  • 83
0
var logo = document.getElementById('rm');
logo.setAttribute('src', 'img/rm2.png');
Aaron
  • 5,137
  • 1
  • 18
  • 20
0

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

function ChangeImage(image_id,path)
{
  document.images[image_id].src = path
}
Nobita
  • 23,519
  • 11
  • 58
  • 87