Search code examples
javascriptdry

Classlist toggle on multiple elements


I have functioning code, but I am sure there is a way to write it cleaner.

My code is far from best practice I assume. Don't repeat yourself principle.

I have tried looking for this problem but can not find an answer.

Here are the expected result and my current code: https://jsfiddle.net/9ednsp6x/

document.getElementById("BtnMoreTotalt").onclick = function() {MoreBtnTotalt()};
function MoreBtnTotalt() {
    document.querySelector(".more-wrapper-totalt").classList.toggle("show");
}

I also wonder, if there is a way so I do not have to use specific id and classnames on every element? Could I only use class "more-wrapper" and skip the IDs?


Solution

  • document.querySelectorAll(".more-button").forEach(element => {
      element.onclick = (e) => {
        const elm = document.getElementsByClassName(e.target.getAttribute("anchor"));
        elm[0].classList.toggle("show");
      };
    });
    .more-wrapper {
      visibility:hidden;
    }
    .more-wrapper.show {visibility:visible};
    <div class="more-wrapper more-wrapper-totalt">
      <div>test1</div>
    </div>
    <a href="#" onClick="return false;">
      <div anchor="more-wrapper-totalt" class="more-button">Mer info</div>
    </a>
    
    <div class="more-wrapper more-wrapper-kvant">
      <div>test2</div>
    </div>
    <a href="#" onClick="return false;">
      <div anchor="more-wrapper-kvant" class="more-button">Mer info</div>
    </a>
    
    <div class="more-wrapper more-wrapper-invb">
      <div>test3</div>
    </div>
    <a href="#" onClick="return false;">
      <div anchor="more-wrapper-invb" class="more-button">Mer info</div>
    </a>
    
    <div class="more-wrapper more-wrapper-barn">
      <div>test4</div>
    </div>
    <a href="#" onClick="return false;">
      <div anchor="more-wrapper-barn" class="more-button">Mer info</div>
    </a>

    You can add the className button with attribute after use this attr click event. It's like clone but i think you need this class another place.