DashG
DashG

Reputation: 1

Why does my button not fire the onclick function after i search for it with a querySelector

Basic HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button class = "hitknop">Hit!</button>
</body>
<script src="index.js" defer></script>

</html>

My JS

const deckinit = "https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1";
const hitknoppie = document.querySelector("hitknop");
let deckId;


async function deckophalen(){
    const response = await fetch (deckinit);
    const deckopties = await response.json();
    deckId = deckopties.deck_id;
    console.log(deckId);
}

deckophalen();

hitknoppie.onclick = async function (){
    const kaartlink = `https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`;
    const response = await fetch (kaartlink);
    const kaart = await response.json();
    console.log(kaart);
} 

I was expecting it to show the result of a single card, but it now just gives me the error that I cannot set properties of null setting 'onclick'.

I tried moving the script tag and adding defer to my Js document without success.

Upvotes: 0

Views: 56

Answers (1)

Markus Konrad
Markus Konrad

Reputation: 21

You must add . because you are calling a class. It must look like this:const hitknoppie = document.querySelector(".hitknop");

Upvotes: 2

Related Questions