diff --git a/expanding-list-web-component/main.js b/expanding-list-web-component/main.js index aadf98c..38a85e0 100755 --- a/expanding-list-web-component/main.js +++ b/expanding-list-web-component/main.js @@ -1,27 +1,22 @@ // Create a class for the element class ExpandingList extends HTMLUListElement { - constructor() { - // Always call super first in constructor - // Return value from super() is a reference to this element - self = super(); - } - connectedCallback() { // Get ul and li elements that are a child of this custom ul element // li elements can be containers if they have uls within them - const uls = Array.from(self.querySelectorAll("ul")); - const lis = Array.from(self.querySelectorAll("li")); + const uls = this.querySelectorAll("ul"); + const lis = this.querySelectorAll("li"); + // Hide all child uls // These lists will be shown when the user clicks a higher level container - uls.forEach((ul) => { + for (const ul of uls) { ul.style.display = "none"; - }); + } // Look through each li element in the ul - lis.forEach((li) => { + for (const li of lis) { // If this li has a ul as a child, decorate it and add a click handler if (li.querySelectorAll("ul").length > 0) { - // Add an attribute which can be used by the style + // Add an attribute which can be used by the style // to show an open or closed icon li.setAttribute("class", "closed"); @@ -35,24 +30,27 @@ class ExpandingList extends HTMLUListElement { newSpan.style.cursor = "pointer"; // Add click handler to this span - newSpan.addEventListener("click", (e) => { + const onClick = (e) => { // next sibling to the span should be the ul - const nextul = e.target.nextElementSibling; + const nextUl = e.target.nextElementSibling; // Toggle visible state and update class attribute on ul - if (nextul.style.display == "block") { - nextul.style.display = "none"; - nextul.parentNode.setAttribute("class", "closed"); + if (nextUl.style.display === "block") { + nextUl.style.display = "none"; + nextUl.parentNode.setAttribute("class", "closed"); } else { - nextul.style.display = "block"; - nextul.parentNode.setAttribute("class", "open"); + nextUl.style.display = "block"; + nextUl.parentNode.setAttribute("class", "open"); } - }); + }; + + newSpan.addEventListener("click", onClick); + // Add the span and remove the bare text node from the li - childText.parentNode.insertBefore(newSpan, childText); - childText.parentNode.removeChild(childText); + childText.parentNode?.insertBefore(newSpan, childText); + childText.parentNode?.removeChild(childText); } - }); + } } }