4

There are at least two ways in JavaScript to change an image:

Using the setAttribute() method.

img.setAttribute('src', 'imgs/' + imgs[i] + '.png');

Writing the src.attribute of the image-element directly.

img.src = 'imgs/' + imgs[i] + '.png'

Both ways work. I've tried it out.

But:

Should I prefer one way over the other and why? Or does it matter at all and I can use what I personally prefer?

bew5
  • 157
  • 1
  • 1
  • 7
  • 2
    duplicate http://stackoverflow.com/questions/3919291/when-to-use-setattribute-vs-attribute-in-javascript – Piotr Kazuś Oct 11 '16 at 07:10
  • You can see this, You will get your answer http://stackoverflow.com/questions/19463647/difference-between-image-setattribute-and-image-src – UDID Oct 11 '16 at 07:10

1 Answers1

10

Or does it matter at all and I can use what I personally prefer?

In this particular case, writing to src, it doesn't matter at all. It's up to you.

Note that there's a big difference reading the value: If you read it with getAttribute("src"), you'll get whatever the actual value of the src attribute is, which may be a relative path. If you read the src property, it will be the resolved path of the image. For instance, say this markup is in http://example.com/path/page.html:

<img src="images/foo.png">

Then

var img = document.getElementById("example");
console.log(img.getAttribute("src")); // "images/foo.png"
console.log(img.src);                 // "http://example.com/path/images/foo.png"

But setting it, you can use either.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
  • 1
    Even though this question is marked as a duplicate and linked to a bunch of existing answered ones, your answer was actually the most helpful to me. Thank you! – mehov Feb 17 '17 at 12:08