0

I'm working on WordPress and Javascript, I want to add a class when you click on the button to show and hide the menu.

This is the html:

<span class="menurwd" id="menurwd"></span>
<ul id="menu-principal" class="menu">
<li>Item</li>
<li>Item</li>
</ul>

the script:

(function() {

    var x = document.getElementById("menu-principal");
    document.getElementById("menurwd").onclick = function activeRwd(){
            if(x.className === "menu"){
                x.className += " active";
            }else{
                x.className = "menu";
            }
        }

})();

In the local installation if it works, but at the time of publishing it generates this error

DCdesign
  • 13
  • 4

1 Answers1

0

The error most likely actually says: "Cannot read property className of null". Which means that x is not pointing to anything. Make sure your JavaScript is moved to just before the body element is closed (</body>) so that by the time the parser encounters the script, the HTML will already have been parsed.

Scott Marcus
  • 57,085
  • 6
  • 34
  • 54