Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

javascript - Uncaught TypeError: Cannot read property 'classList' of null at HTMLDivElement.<anonymous>

I'm facing an issue with the error described in the title of my question. When I click on the burger for my mobile menu, this error message comes up: Uncaught TypeError: Cannot read property 'classList' of null at HTMLDivElement.. Here is my JS Code:

window.onload = function(){
const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');
    const navLinks = document.querySelectorAll('.nav-links li');
    
    burger.addEventListener('click', () => {
        // Toggle Nav
        nav.classList.toggle('nav-active');

        // Animate Links
        navLinks.forEach((link, index) => {
            if (link.style.animation) {
                link.style.animation = '';
            } else {
                    link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
                }
        });
        // Burger Animation
        burger.classList.toggle('toggle');

    });
    
}

navSlide();

}

,... this is my HTML:

<header>
  <div class="logo">
    <h1 class="logo-text">Title</h1>
  </div>
  <ul class="nav">
    <li><a href="#">Home</a></li>
    <li><a href="#">Item1</a></li>
    <li><a href="#">Item2</a></li>
    <li><a href="#">Item3</a></li>
  </ul>

  <div class="burger">
    <div class="line1"></div>
    <div class="line2"></div>
    <div class="line3"></div>
  </div>
</header>

In CSS I have a class called .nav-active and a class .toggle which should work when I open the menu. I'm using this JS as an additional file in Joomla.

I hope you can help me! Thank you!

question from:https://stackoverflow.com/questions/65849502/uncaught-typeerror-cannot-read-property-classlist-of-null-at-htmldivelement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your class is incorrect

const nav = document.querySelector('.nav-links');
const navLinks = document.querySelectorAll('.nav-links li');

but you use:

<ul class="nav">

So when

nav.classList.toggle('nav-active');

is called, the "nav" object is not defined.

Change the unordered list to:

<ul class="nav-links">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...