Home > OS >  Please i dont know where i get it wrong
Please i dont know where i get it wrong

Time:01-31

const quoteText = document.querySelector("quote")
quoteBtn = document.querySelector("button")

// random quote function
function randomQuote() {

    //Fetching random quote from API and parsing it into Js Object
    fetch("https://api.quotable.io/random").then(res => res.json()).then(result=>{
        console.log(result);
        quoteText.innerText = result.content;
    }); 
    
}

quoteBtn.addEventListener("click", randomQuote);

I expect it to next the quote as i am clicking on it, but rather it is displaying in the console as "Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText')"

CodePudding user response:

If you use document.querySelector(), you need to use a class or an id, unless your target is a native html element. <quote> is not a native html element. So I guess you need to use:

const quoteText = document.querySelector(".quote")

Mind the . in document.querySelector(".quote")

CodePudding user response:

It looks like you are trying to fetch a random quote from an API and display it on a website when a button is clicked.

There's a syntax error in the code, the quoteBtn declaration is missing a var or const keyword, which should be fixed:

const quoteText = document.querySelector("quote");
const quoteBtn = document.querySelector("button");

Additionally, make sure that the elements with the quote and button class names actually exist in your HTML, otherwise quoteText and quoteBtn will be null and the code will throw an error when trying to add the click event listener.

  • Related