Search code examples
javascriptforeachtoggleaddeventlistenerqueryselector

Toggle forEach child div classes in Javascript.(bgcolor of the text is changing but bgcolor of those divs NOT)


Hy everyone,

I have this hamburger menu lines, and i want to change their color when i click it. I tryed with addEventListener + toggle class, and also with simple element.style.backgroundColor for those divs(i added same class for all), but is not working in either those cases. Though, the text color is changing, but the background color of those divs is not). Below is the code.

Thank you very much.

const hamburgerMenu = document.querySelector(".hamburger-menu");
const hamburgerMenuLines = document.querySelectorAll(".hamburger-menu div");

hamburgerMenu.addEventListener('click', () => {
  // (code to open menu fullscreen which works fine)
  hamburgerMenuLines.forEach((line) => {
    line.classList.toggle("changeHamburgerMenuLinesColor");
  });
});
.hamburger-menu div {
  width: 100%;
  height: 2px;
  border-radius: 30%;
  background-color: black;
  position: relative;
  margin-top: 11px;
}

.changeHamburgerMenuLinesColor {
  background-color: white;
  color: white;
}
<div class="hamburger-menu">
  <div>Text</div>
  <div>Text</div>
  <div>Text</div>
</div>


Solution

  • Problem is because of CSS specificity. When two selectors apply the same style on an element, the one with more specificity takes precedence.

    In your case, .hamburger-menu div is more specific selector as compared to .changeHamburgerMenuLinesColor, so background color set using the first selector, i.e. "black", will be applied on each div element.

    To solve the problem, you need to increase the specificity of the second selector. Writing the second selector as shown below will make the specificity of both selectors equal and the one that comes later in the order from top to bottom, will take precedence.

    div.changeHamburgerMenuLinesColor {
       background-color: white;
       color: white;
    }
    

    Tip: Browser dev-tools provide help to debug such issues. Invest some time to learn how to use them to your advantage.