5

I use the querySelector in JS to select html markup that I filled in with a JS script. However, anytime I try to store the divs with a class of .card in the const questionCard, I get null.

Why can't I select the cards?

HTML:

<div class='card-container'></div>

JS:

const questionBlock = document.querySelector('.card-container');
const questionCard = document.querySelector('.card');

function build() {
    let output = [];

    ...some unimportant code here...

      output.push(
        `
          <div class='card'>
            <div class='question'>${current.question}</div>
            <div class='answers'>${answers.join('')}</div>
          </div>
        `
      );
    })

    questionBlock.innerHTML = output;
}

build();
bird_blue03
  • 157
  • 2
  • 9

2 Answers2

3

You need to call document.querySelector('.card') after calling build(). It cannot find HTML elements that do not exist yet.

const questionBlock = document.querySelector('.card-container');

function build() {
    let output = [];

    ...some unimportant code here...

      output.push(
        `
          <div class='card'>
            <div class='question'>${current.question}</div>
            <div class='answers'>${answers.join('')}</div>
          </div>
        `
      );
    })

    questionBlock.innerHTML = output;
}

build();

const questionCard = document.querySelector('.card');
Dennis
  • 13,205
  • 2
  • 43
  • 57
1

An alternative to the more correct answers is:

const questionCard = document.getElementsByClassName('card');

now: questionCard is a live HTMLCollection, and questionCard[0] will be the first element with class including card

Jaromanda X
  • 47,382
  • 4
  • 58
  • 76