Why this menu toggle behavior

I want to build a responsive menu, showing a Hamburger menu at a certain width with an Eventlistener which triggers toggle behaviour. Why is it working only when between button Tag and nav class is an img?
If I comment out, at onClick on Hambuger Menu, the menu is visible – but does not go away by clicking again.

This is the HTML:

      <!-- <div class="container row"> -->
        <button class="nav-toggle">
          <span class="hamburger"></span>
<-- If this is commented out, toggle does not work. -->
          <img src="img/logo.svg"  /> 
<--End of "issue point -->
        <nav class="nav">
            <li ><a href="#" >Home</!--></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>

This is the JS

const navToggle = document.querySelector('.nav-toggle');
const nav = document.querySelector('.nav');

navToggle.addEventListener('click', () => {

Because I have no clue, why this happens I have no Idea, which part of the CSS I should show.

It is not neccessarily an img tag which is needed. I tried H1 also – and then it works again.

It seems to be just neccessary, that between and is another element. Could anyone explain, why this happens?

Many thanks!

Hi @sh11, I don’t see an issue with your JS but the problem is most likely caused by your HTML not being well-formed – you commented out the opening container div tag but left the closing one.

There was some typos and no css, but here is a start:


That seems to be working ok. Can you explain what’s wrong with that demo?

Hi @PaulOB and @sibertius, yes, it works. But I don’t understand, why, in my code, it is neccessary to have some element in between – lik an img, or an p or an H1 tag. The img tag can be empty. But the h1 or p tags have to be filled to work.
I solved this issue by a hint @m3g4p0p gave. When wrapping everything into a div, the menu is opening as intended. (This is the related HTML.

<-- I need to wrap everything into the container -->
   <div class="container">
        <p class="header-logo"><a href="<?php echo site_url() ?>"><?php bloginfo(name)?></a></p>

        <button class="nav-toggle" aria-label="open navigation">
                <span class="hamburger"></span>
<!-- Visible on wide -->
       <nav class="header-menu-wide nav">
                    'theme_location' => 'header-menu'

But I don’t understand why I need to wrap it into a container - or if I dont’t do it, why I have to place an element between button and nav.
Thank you very much for your interest and help!


We need to see the exact version where you have this problem.

As you can see your demo does not exhibit this behaviour (with or without the container or the comment added) so there is likely something else going on.

if you can make a demo that exhibits the problem then we can provide better answers and be more helpful :slight_smile:


You do not need a container in this example. And you can simplify this further: