-1

guys. Im trying to show/hide a mobile menu on click, but I don't know what I am doing wrong. If you may help me, I'd be really thankful:

   <script>
    var menuToggle = document.getElementsByClassName('menuToggle');
    var nav = document.getElementsByClassName('responsive-navigation');
    menuToggle.addEventListener('click', () => {
        if (nav === 'block') {
            nav.style.display = "none";
        } else {
            nav.style.display = "block";

        }
    });
</script>

1 Answers1

1

getElementsByClassName() returns collection. You have to use specific index. I think you also mistakenly comparing the element itself to the property value in the if condition.

Though I prefer using querySelector():

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned

var menuToggle = document.querySelector('.menuToggle');
var nav = document.querySelector('.responsive-navigation');
menuToggle.addEventListener('click', () => {
  if (nav.style.display === 'block') {
    nav.style.display = "none";
  } else {
    nav.style.display = "block";
  }
});
Mamun
  • 66,969
  • 9
  • 47
  • 59