Javascript how to pass var into setAttribute

  javascript, setattribute

I try to make a little dice game (as an challenge for a course).
The code should just replace 2 images everytime I reload the page.

The (theoretical) code works perfectly inside the chrome developer snippet:

var diceImages = ["./images/dice1.png", "./images/dice2.png", "./images/dice3.png", "./images/dice4.png", "./images/dice5.png", "./images/dice6.png"];

var n = Math.random();
var dice = Math.floor(n*diceImages.length);

var diceRoll = diceImages[dice];

console.log(diceRoll);

But then if I try to pass the var diceRoll into setAtttribute like this, it doesn’t work:

var diceImages = ["./images/dice1.png", "./images/dice2.png", "./images/dice3.png", "./images/dice4.png", "./images/dice5.png", "./images/dice6.png"];

var n = Math.random();
var dice = Math.floor(n*diceImages.length);

var diceRoll = diceImages[dice];


document.querySelectorAll("img")[0].setAttribute("src", "diceRoll");

How can I pass a var into setAttribute?

Thanx for your help.

Source: Ask Javascript Questions

LEAVE A COMMENT