0

I have this problem, i'm noob with js so i can't understand how it works getElementByClassName. when i use only id it's work perfect, but now with getElementByClassName doesnt work.

How can I make it work?



<ul>
  <li>Item 2</li>
  <li id="item">
    Item 2
    <ul class="sub-menu">
      <li>Sub Item<li/>
    </ul>
  </li>
  <li>Item 2</li>
</ul>


(function (d) {
    let item = d.getElementById('item');
    let subMenu = d.getElementsByClassName('sub-menu');
    if(item!=null){
        item.addEventListener('click', () => subMenu.classList.toggle('opened'));
    }
})(document);
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • You have an array in item, you need to get the element you want it of it [0] in your case. – cloned Apr 28 '20 at 20:07
  • As Eugen said. `getElementsByClassName` gets ALL elements with that class name. If you want only the first such element, you access it with the bracket syntax and its index (`[0]` for the first element), the same way you would get an element of an array (although this is not, technically, an array.) Check out MDN for more: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – Cat Apr 28 '20 at 20:10

1 Answers1

-1

getElementsByClassName returns an array, you probably want the first element:

(function(d) {
      let item = d.getElementById('item');
      let subMenu = d.getElementsByClassName('sub-menu');
      if (item != null) {
        item.addEventListener('click', () => subMenu[0].classList.toggle('opened'));
      }
    })(document)
EugenSunic
  • 13,162
  • 13
  • 64
  • 86