tom
tom

Reputation: 35

Can you use querySelector in Javascript to select a subset of a previously made selection?

I am trying to program a quiz, where all the questions have a 'question' class and the answers within the questions have an 'answer' class, together with a 'correct' or 'incorrect' class.

What I would like to do is make a loop that goes over all the questions, and for each question selects the right and wrong answers into groups. I (try to) do this by "stacking" querySelectors on top of each other, by first selecting the questions, then selecting all answers of a question and finally selecting for right and wrong answers. For some reason though, my code does not work:

let right = 0;
let wrong = 0;
let questions = document.querySelectorAll('.question');
let q = questions.length;

///*
for (let k = 0; k < q; k++)
{
  let answers = questions[k].querySelectorAll('.answer');

  let right_answer = answers.querySelector('.correct');
  let wrong_answers = answers.querySelectorAll('.incorrect');

  right_answer.addEventListener('click', function() {
    right++;
  });
  let len = wrong_answers.length;
  for (let l = 0; l < len; l++)
  {
    wrong_answers[l].addEventListener('click', function() {
      wrong++;
    });
  }
}

Can anyone help me? I could probably work around it, but this has become a point of pride... ;-)

PS: the console seems to like it until this line, but I just cannot figure out the problem here...

let wrong_answers = answers.querySelectorAll('.incorrect');

Upvotes: 2

Views: 276

Answers (2)

uingtea
uingtea

Reputation: 6554

if it input type radio you just need to count element class that checked

function $_(selector) {
  return document.querySelectorAll(selector);
}

$_('input[type="radio"]').forEach(function(answer) {
  answer.addEventListener('change', function() {
    right = $_('input.correct:checked').length;
    wrong = $_('input.incorrect:checked').length;
  })
})

Upvotes: 1

Allan J.
Allan J.

Reputation: 530

Answers is a nodeList (Array like). You could select wrong answers it with:

let wrong_answers = questions[k].querySelectorAll('.answer.incorrect');

Upvotes: 1

Related Questions