Home > Back-end >  Issues with toggling an class with javascript
Issues with toggling an class with javascript

Time:10-23

I'm creating my first little project and I'm having a button toggle a class on an element. When I use the toggle I can see in the browser that chrome shows as if it changed but it changes to the same thing that's on it right now. I've even tried toggling a different random class onto it and cannot get it to toggle that on or off. Not quite sure what I'm doing wrong.

Heres my javascript:

document.querySelectorAll(".open").forEach((item) => {
  item.addEventListener("click", (event) => {
    event.target
     .parentElement
     .parentElement
     .parentElement
     .parentElement
     .children[1]
     .classList.toggle("hidden");
  });
});

And my HTML code

<div >
  <ul >
    <li >
      <div >
        <h1 >27574-10</h1>
        <div >
          <button  id="open1">
            <img
              
              id="open1"
              src="img/svg/plus-empty.svg"
              alt="Expand specs"
            />
          </button>
          <button  id="print1">
            <img
              
              id="print1"
              src="img/svg/printer-empty.svg"
              alt="Print"
            />
          </button>
        </div>
      </div>
      <div
        
        id="specs-container-1"
      ></div>
    </li>
  </ul>
</div>

CodePudding user response:

You use querySelectorAll(".open") which will select both <button > ... </button> and the image inside <img ... \> This means that when you click the button, the event is fired twice (one for the button, one for the image).
The code which toggles the class is actually correct, but it toggles twice which means there's no effect
Here is the fixed HTML

<div >
  <ul >
    <li >
      <div >
        <h1 >27574-10</h1>
        <div >
          <button  id="open1">
            <img
              id="open1"
              src="img/svg/plus-empty.svg"
              alt="Expand specs"
            />
          </button>
          <button  id="print1">
            <img
              
              id="print1"
              src="img/svg/printer-empty.svg"
              alt="Print"
            />
          </button>
        </div>
      </div>
      <div
        
        id="specs-container-1"
      ></div>
    </li>
  </ul>
</div>

If you plan to do the same thing with the print button/img then make sure to remove from it aswell.

CodePudding user response:

certainly, something like this would be preferable

document.querySelectorAll("button.open").forEach(item => {
  item.addEventListener("click", event => {
    event
      .currentTarget.closest(".title") // currentTarget
      .nextElementSibling
      .classList.toggle("hidden");
  });
});
  • Related