-1

When I use this code to add & remove the style , Part ( else ) only works and sets (display) to block, But it will not return the class if clicked again. what's wrong?

var navDropDown = document.querySelectorAll('.menu-item-has-children > a');
for (let i = 0; i < navDropDown.length; i++) {
  navDropDown[i].addEventListener('click', (e) => {
    if (navDropDown[i].nextElementSibling.style.display = 'none') {
      this.nextElementSibling.style.display = 'block';
    } else {
      this.nextElementSibling.style.display = 'none';
    }
  })
}
Salvator3e
  • 31
  • 5

1 Answers1

1

The line:

if (navDropDown[i].nextElementSibling.style.display = 'none') {

uses a single =, instead of ==. In Javascript, = is an assignment, which returns the value assigned. 'none' being not empty, it is converted into true, and thus the else will never be executed.

Derlin
  • 9,572
  • 2
  • 32
  • 53
  • 1
    This topic is ***very*** well-covered by previous questions and answers. We don't need more, just close votes (and perhaps a comment for clarity if needed). – T.J. Crowder Aug 24 '20 at 07:16