0

i want to add toggle class to two elements a li and a div but i can only get it to work on the div

var list = document.getElementsByClassName("list");
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    list.classList.toggle("active");
    var panel = this.nextElementSibling;

    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  });
}
<ul class="collapsible popout">
    <li class="list">
        <div class="accordion">Section 1</div>
        <div class="panel">
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
    </li>
    <li class="list">
        <div class="accordion">Section 2</div>
        <div class="panel">
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
    </li>
    <li class="list">
        <div class="accordion">Section 3</div>
        <div class="panel">
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
    </li>
</ul>

i cant get seem to get both to the li class list and the div accordion to toggle active at the same time where am i going wrong sorry not very skilled when it comes to javascript

fernandosavio
  • 9,849
  • 4
  • 24
  • 34
  • 4
    `Cannot read property 'toggle' of undefined",` – epascarello Sep 18 '18 at 14:07
  • Most likely a dupe of https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method – epascarello Sep 18 '18 at 14:08
  • Trying to set the class on both elements is not a good design. Set the active class only on the accordion element itself. If you want to change the appearance of other related elements, there are css rules to differentiate based on what classes an immediate child element has. – NineBerry Sep 18 '18 at 14:17

1 Answers1

3

Use this.parentNode.classList.toggle("active"); instead of list.classList.toggle("active");

https://jsfiddle.net/nimittshah/t5ubLj40/

Nimitt Shah
  • 4,477
  • 2
  • 10
  • 21