0

I'm currently transitioning a web-app from using jQuery to pure Javascript and think I have run into a problem with my understanding of Javascript.

I'm attempting to apply an attribute to all of the child elements of an unordered list, my code looks like this:

function openDropdown(elmnt) {
  console.log("dropdown menu clicked!");
  let listItems = elmnt.children
  let firstListItem = elmnt.firstElementChild
  console.log(listItems);
  console.log(firstListItem);
  if (firstListItem.style.display !== "none") {
    listItems.style.display = "none";
  } else {
    listItems.style.display = "block";
  }
}
ul {}

ul li {
  display: none;
}
<div id="menu-items">
  <ul class="dropdown" onclick="openDropdown(this)">Title of UL
    <li><a href="">Item</a></li>
    <li><a href="">Item</a></li>
    <li><a href="">Item</a></li>
    <li><a href="">Item</a></li>
  </ul>
</div>

As I understand it the function openDropdown should:

  1. Check to see if the first li has is display: none
  2. If it doesn't, assign it display: none
  3. If it does, assign it display: block

The console logs both elmnt.children and firstElementChild correctly, but I get the error cannot set property 'display' of undefined I'm assuming that I'm using the property .children incorrectly but I can't figure out how to fix this function. How would I go about making this function work?

Tadgh
  • 19
  • 7
  • A `
      ` directly inside of a `
        ` doesn't make sense
    – Pointy Apr 25 '20 at 18:41
  • 2
    And you cannot use a list of elements to set properties of each item; you have to do the iteration through the list yourself. – Pointy Apr 25 '20 at 18:44
  • good catch @Pointy that was supposed to be a div – Tadgh Apr 25 '20 at 20:22
  • 2
    `listItems` does not have a `.style` property. It's a collection, but only individual elements (such as `firstListItem`) have styles. You need a loop. The duplicate I've chosen is about dom selection methods (and probably useful if you're transitioning from jQuery, which doesn't distinguish single elements, always keeping a collection) but the issue and solution are the same for `.children`. – Bergi Apr 25 '20 at 20:23
  • @Bergi, thanks very much, that's it. – Tadgh Apr 27 '20 at 14:17

0 Answers0