Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.querySelector returns null

Tags:

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();
like image 594
bird_blue03 Avatar asked Oct 12 '17 00:10

bird_blue03


2 Answers

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');
like image 103
Dennis Avatar answered Sep 30 '22 14:09

Dennis


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

like image 39
Jaromanda X Avatar answered Sep 30 '22 14:09

Jaromanda X