I am having trouble getting my elements by ID, as they keep returning null.
I've noticed some people have this problem with the script loading before the DOM but I'm not sure how to fix this issue from an external js script.
I've tried a few different variations but would like to keep my js scipts external if possible. I've also tried changing the listener, element, id, etc.
Any and all help is appreciated. I know this question has been asked a couple of times but I couldn't find an answer in terms I understand, but please direct me to threads of this caliber if they exist. Thank you!
Note: I am currently learning js, having known HTML and CSS. Not sure if this is something jquery could take care of.
let computerSelection;
let playerSelection;
let rockbtn = document.getElementById("button");
function computerPlay() {
computerSelection = Math.floor(Math.random() * 3);
switch (computerSelection) {
case 0:
computerSelection = "ROCK";
break;
case 1:
computerSelection = "PAPER";
break;
default:
computerSelection = "SCISSORS"
}
return computerSelection;
}
function playGame(computerSelection, playerSelection) {
playerSelection = chooseForMe();
computerSelection = computerPlay();
console.log(`You threw ${playerSelection} and computer threw ${computerSelection}`);
if (computerSelection === playerSelection) {
console.log("Tie Game. Go Again");
}
if (playerSelection === "ROCK" && computerSelection === "SCISSORS") {
console.log("You win!");
} else if (playerSelection === "ROCK" && computerSelection === "PAPER") {
console.log("You lose!");
} else if (playerSelection === "PAPER" && computerSelection === "ROCK") {
console.log("You win!");
} else if (playerSelection === "PAPER" && computerSelection === "SCISSORS") {
console.log("You lose!");
} else if (playerSelection === "SCISSORS" && computerSelection === "PAPER") {
console.log("You win!");
} else if (playerSelection === "SCISSORS" && computerSelection === "ROCK") {
console.log("You lose!");
}
}
rockbtn.addEventListener("click", playGame);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Smokum&display=swap" rel="stylesheet">
<script src="java.js"></script>
<title>Java Page</title>
</head>
<header>
<div class="container" <p id="header">Rock Paper Scissors?</p>
</div>
</header>
<body>
<button id="button">Rock</button>
<button id="paperbutton">Paper</button>
<button id="scissorsbutton">Scissors</button>
</body>
</html>