728x90
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomImageSource = "images/dice" + randomNumber1 + ".png";
var image1 = document.querySelectorAll("img")[0]
var image2 = document.querySelectorAll("img")[1]
image1.setAttribute("src", randomImageSource)
// Image 1
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomImageSource = "images/dice" + randomNumber1 + ".png";
var image1 = document.querySelectorAll("img")[0];
// var image2 = document.querySelectorAll("img")[1];
image1.setAttribute("src", randomImageSource)
// Image 2
var randomNumber2 = Math.floor(Math.random()*6)+1;
var randomImageSource2 = "images/dice" + randomNumber2 + ".png";
document.querySelectorAll("img")[1].setAttribute("src", randomImageSource2)
// image2.setAttribute("src", randomImageSource2);
// If player 1 wins
if (randomNumber1 > randomNumber2) {
document.querySelector("h1").innerHTML = "🚩 Player 1 Wins!";
} else if (randomNumber1 < randomNumber2) {
document.querySelector("h1").innerHTML = "Player 2 Wins! 🚩";
} else {
document.querySelector("h1").innerHTML = "Draw!";
}
By looking at the code above, for two images, different approachs are applied to each other regrading Element.setAttribute();
For image1, make a variable for the attribute to change, then change its attribute to newly created one, i.e. "randomImageSource".
For image2, not creating a varible, just directly change the attribute to change.
728x90
'Web Dev' 카테고리의 다른 글
Advanced Javascript and DOM Manipulation - Drum kit (0) | 2021.01.06 |
---|---|
The Document Object Model (DOM) (0) | 2021.01.03 |
Intermediate Javascript (0) | 2021.01.02 |
Intermediate CSS - PART III (Refactoring II, Selector Priority) (0) | 2020.12.27 |
Intermediate CSS - PART II (Media Query Breakpoints, Refactoring, Selectors) (0) | 2020.12.26 |
댓글