简体   繁体   中英

How do I select all elements with the same class?

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

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 :)";
  }
}

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 );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM