-2

I read up about this and it seems that query selector isn't finding the class. Thus, returning null. I tried the last solution provided here: document.querySelector(…) is null error and the console didn't give any errors. However, nothing happens. Trying to

cosole.log(document.querySelector('wordImage');

doesn't display any messages to the console.

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <style>
        .exa-title{
            font-style: italic;
            margin-left:10px;
            color: dimgray;
        }
    </style>
    <body>
        <img class="word-image"src="" alt="">
        <span class="ex-title"></span><span class="ex-sentence"></span>
        <input class="word-input" type="text" name="" autofocus>

<script>

window.addEventListener('load', init);

    const vocabularyList = [
      {
        image: "https://media.istockphoto.com/photos/red-apple-with-leaf-isolated-on-white-background-picture-id185262648?k=6&m=185262648&s=612x612&w=0&h=u9rMspGGTOkgUSzZ6INtT_Ww4NpGz9zHMGRmIJJjBqQ=",
        word: "apple",
        example: "The red apple."
      },
      {
        image: "https://upload.wikimedia.org/wikipedia/commons/8/88/Bright_red_tomato_and_cross_section02.jpg",
        word: "tomato",
        example: "The red tomato."
      }
    ];

function init(){
    //DOM  variables
    const wordImage = document.querySelector('word-image');
    const ex_title = document.querySelector('ex-title');
    const ex_sentence = document.querySelector('ex-sentence');
    const wordInput = document.querySelector('word-input');
    // Load the first object from the array
    showCard(vocabularyList);
    //Start matching on word input
    wordInput.addEventListener('input', matchWords);
}
// Pick and show random word

function showCard(vocabularyList){
    //Generate random array index
    const randIndex = Math.floor( Math.random() * vocabularyList.length);
    //Output the random word
    wordImage.src = vocabularyList[randIndex].image;

}

function matchWords(){
    if(wordInput.value === vocabularyList[randIndex].word){
        // ex_title.innerHTML = "p. ej.";
        ex_sentence.innerHTML = vocabularyList[randIndex].example;
    }
}

</script>


    </body>
</html>
Simple
  • 437
  • 7
  • 19

1 Answers1

3

querySelector accepts a CSS selector. This code uses a tag selector:

const wordImage = document.querySelector('word-image');

That is, it looks for an element with the tag word-image, like this:

<word-image>...</word-image>

A class selector starts with a .:

const wordImage = document.querySelector('.word-image');

See:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I can't believe I didn't notice that. however it still getting null after correctly selecting the class. – Simple Jan 27 '19 at 10:47