Reputation: 67
I'm building this game with JavaScript. It's a simple game: you get asked what number1 + number2 equals, and you have 4 different options to choose (only one answer is correct).
I have 4 different divs for the 4 different options, all with the class '.field-block'. This is what I tried doing:
var choice = document.querySelector('.field-block');
choice.addEventListener('click', getChoice);
function getChoice(){
if(choice.innerHTML != result){
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else{
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be affraid to try again :)";
}
}
However, by doing this I'm only able to click on the first 'field-block' divs and not on the other ones.
Here is the full codepen of my project:
https://codepen.io/teenicarus/pen/Oxaaoe
How do I select all divs, so that the user can click on all of them and not just the first one ?
I appreciate all responses
Upvotes: 0
Views: 1896
Reputation: 68433
However, by doing this I'm only able to click on the first 'field-block' divs and not on the other ones.
querySelector
returns only one element, you need to use querySelectorAll
var choices = document.querySelectorAll('.field-block');
[].slice.call(choices).forEach( function( choice ){ //iterate and assign event handler to them individually
choice.addEventListener('click', function(){
getChoice(choice);
});
});
function getChoice(choice){
if(choice.innerHTML != result){
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else{
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be affraid to try again :)";
}
}
Or more simpler version in jquery
$('.field-block').click( function(){
getChoice( this );
});
Upvotes: 1
Reputation: 337714
The issue is because querySelector()
returns a single item. Use querySelectorAll()
to retrieve all instances. You can then loop through them:
document.querySelectorAll('.field-block').forEach(function(field) {
field.addEventListener('click', function() {
getChoice(this);
});
})
function getChoice(choice){
if (choice.innerHTML != result) {
after.classList.remove('hide');
after.classList.add('wrong');
after.innerHTML = 'Ooh you were wrong ! Play again to give it another shot !';
} else {
after.classList.remove('hide');
after.classList.add('correct');
after.innerHTML = "Good job ! Don't be afraid to try again :)";
}
}
Upvotes: 2