Cannot read property "addEventListener" null error in javascript

I am trying to animate open (+) and closed (x) buttons for main navigation. It is not working correctly and I am getting this error.

Uncaught TypeError: Cannot read property addEventListener of null

JavaScript

document.querySelector( "#nav-toggle" ).addEventListener( "click", function() {
  this.classList.toggle( "active" );
});

      

Html

<a id="nav-toggle"   href="#navi" data-toggle="collapse" 
 data-target="#bs-example-navbar-collapse-1">
    <span></span>
</a>

      

+3


source to share


1 answer


Your code should work. It could be a javascript run problem or a conflict with your data library. The crash library might overwrite your ID. Try using a page inspector like firebug to see if the id changes after loading.

Below your code toggles the link to red.



document.querySelector( "#nav-toggle" ).addEventListener( "click", function() {
  this.classList.toggle( "active" );
});
      

.active {color:red}
      

<a id="nav-toggle"   href="#navi" data-toggle="collapse" 
 data-target="#bs-example-navbar-collapse-1">
    <span>test</span>
</a>
      

Run codeHide result


0


source







All Articles