19

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

6 Answers 6

34

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?

Sign up to request clarification or add additional context in comments.

2 Comments

dang it, beat me by 8 seconds :)
:) Yea the JS/JQuery questions really have too many people fighting to shoot an answer.
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');
    }
};

Comments

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

Comments

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
}

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.