5

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
  • 167
  • 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

2 Answers2

12

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
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 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! – ᴍᴇʜᴏᴠ Feb 17 '17 at 12:08
0

If you want to select the random image using Js then we have to do the following step...

Step 1: Generate a random number using Math.random then multiply with a number it's totally up to you for me dice game I have multiplied by 6.

Step 2: Now we get the number in huge decimal numbers like 5.39434703437, so to truncate the decimal part we will use Math.floor function. As we know that when generating a random number it generates the number between 0-1 but we will never get 1 as a random number like when we multiply by 6 we will not get 6 as a random number we will get between 0-6. So to solve this problem we will add 1 to it.

Step 3: Now add a random number in the image's name.

Step 4: The last we can do is set an Attribute whenever we will refresh the webpage we will get dice images

//Step 1-2
var randomNumber1=Math.floor((Math.random())*6);
randomNumber1=randomNumber1 + 1;

//Step 3
var firstImageSrc="images/dice"+randomNumber1+".png";

///Step 4
document.querySelector("img.img1").setAttribute("src",firstImageSrc);
<img class="img1" src="images/dice6.png">