I was making a box guessing game where there was multiple divs and one of them was the correct one.
The user should click a box to see if it was the correct box or not.
The HTML:-
<body>
<div class = "wrapper">
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>
<div id="box4" class="box"></div>
<div id="box5" class="box"></div>
<div id="box6" class="box"></div>
</div>
</body>
I gave all the boxes the (box) class and gave each box its own ID
then I made a variable that stores a random number (randomNum) which is from 0-5 and made a variable for each box and made an array called boxes so tha the correct box is boxes[randomNum]
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
const box3 = document.getElementById("box3");
const box4 = document.getElementById("box4");
const box5 = document.getElementById("box5");
const box6 = document.getElementById("box6");
let boxes = [box1, box2, box3, box4, box5, box6];
let randomNum = Math.floor(Math.random() * 6);
now I need to check if the box that is clicked is the correct box or not
I tried making a function that checks if the box that is clicked is equal to the boxes[randomNum] but I had trouble with referencing the clicked box
Does anyone know how I can get the clicked box?
4
Answers
To do what you require you can determine the index of the clicked
.box
within its parent usingparentNode.children
, and comparing this to the random number you generated:When you subscribe to the click event, the
event
object is passed as the first parameter.event
object has propertytarget
that contains the element that has been clicked. You can use methodindexOf
of an Array to find your div, as they are equal by reference:Use querySelectorAll instead of getting each element by its id and then use addEventListener generate your randomNumber and concatenate the
"box"
string to the number then compare with the selected boxid
to be able to tell which box was clicked.Edit: moved the random number generator inside the eventListener so that it generates a new number, everytime you pick a new box
You do not need ID attributes. You just need to generate a random integer from 1 to 6, and determine if the box is correct based on the click target.