2

At first, sorry for my english, but can u tell me what am i doing wrong? error:

Uncaught TypeError: Cannot read property 'classList' of null

// get 'hamburger' class from html
const hamburger = document.querySelector('.hamburger');

// handle click on hamurger and add class 'hamburger-active' to it
function handleClick(){
    hamburger.classList.toggle('hamburger-active');
}
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Candyy
  • 51
  • 1
  • 3
  • 2
    Share your HTML code – Sajeeb Ahamed Mar 21 '20 at 15:34
  • 1
    The error means that `document.querySelector` didn't find the element `.hamburger`. It's either because: a) that element doesn't exist, b) the class name provided has a typo, or c) the script runs before the element is created. – ibrahim mahrir Mar 21 '20 at 15:34
  • 3
    Most likely: [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) – Andreas Mar 21 '20 at 15:37
  • 1
    Where do you include the script? In the header or at the bottom of the body? – ibrahim mahrir Mar 21 '20 at 15:38

1 Answers1

2

An element with the class name .hamburger was not found, so the variable hamburger is null. Because the variable is null, you can't read its classList property (a null value doesn't have any properties).

To fix the error, ensure that the DOM contains an element with the class name .hamburger when the first line of your code (const hamburger = document.querySelector('.hamburger');) is run. You can add console.log(hamburger); to the next line to check the variable's value.

You can also check whether the variable is null before attempting to toggle the class hamburger-active:

function handleClick(){
    if (hamburger !== null){
        hamburger.classList.toggle('hamburger-active');
    }
}
Matias Kinnunen
  • 7,828
  • 3
  • 35
  • 46
  • That's the explanation for the error. But why is this also an answer and not only a comment? – Andreas Mar 21 '20 at 15:36
  • 2
    Ok, i understand, but the problem is that element with class .hamburger EXISTS in html so u know. – Candyy Mar 21 '20 at 15:39