0
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')"

CBroe
  • 91,630
  • 14
  • 92
  • 150
  • 1
    There's no `` element in your markup at the time the script is run. – Teemu Jan 31 '23 at 11:14
  • 1
    error msg is pretty clear. `quoteText` is null – Chris G Jan 31 '23 at 11:15
  • 2
    Please go read [ask], and [mre]. The former already has some hints for you on the very first thing you got "wrong" here - the question title. – CBroe Jan 31 '23 at 11:17
  • You have to use a `.` or `#` in document.querySelector("quote"). Like `document.querySelector(". quote")` – Kurt Van den Branden Jan 31 '23 at 11:20
  • The error message is clear - `quoteText` does not contain the reference to any element, but only `null`. So your question is most likely to be considered a duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – CBroe Jan 31 '23 at 11:23
  • To my best understanding, i have tried everything i knew it is not working, yet all provided solutions by bosses here is not working too – Abdussomad Sikirullah Jan 31 '23 at 11:27

2 Answers2

1

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.

phuzi
  • 12,078
  • 3
  • 26
  • 50
0

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")

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85