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:
- Check to see if the first li has is display: none
- If it doesn't, assign it display: none
- 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?
` directly inside of a `
– Pointy Apr 25 '20 at 18:41` doesn't make sense