Currently, I am in the process of creating a list of anchor links that contain nested anchor links, and there are a few functionalities that I am looking to implement.
Upon clicking on a link:
- Add a class of "current"
- Remove the class of "current" from any other link or nested link
- If the item has children, toggle the value of a data-attribute (e.g., data-children="visible" or data-children="hidden")
- Ensure that the anchor link functionality remains intact
It is worth mentioning that whether the "data-children" attribute is present on the parent a.link or on the div.children is irrelevant to me.
HTML
<ul>
<li><a href="#l1" class="link">Level 1</a></li>
<li><a href="#l2" class="link" data-children="hidden">Level 2</a>
<div class="children">
<ul>
<li><a href="#l2-1" class="link">Level 2.1</a></li>
<li><a href="#l2-2" class="link" data-children="hidden">Level 2.2</a></li>
<li><a href="#l2-3" class="link">Level 2.3</a></li>
</ul>
</div>
</li>
<li><a href="#l3" class="link">Level 3</a></li>
</ul>
JavaScript
let el = document.querySelectorAll('.link');
for (let i = 0; i < el.length; i++) {
el[i].onclick = function() {
let c = 0;
while (c < el.length) {
el[c++].className = 'link';
}
el[i].className = 'link current';
let x = el.getAttribute('data-children');
if (x === 'visible') {
el.setAttribute('data-children', 'visible');
} else {
el.setAttribute('data-children', 'hidden');
}
};
}
The desired outcome is to enable any link to be marked as the "current" link, with the ability to toggle the display of any or all child links.
By clicking on a parent link, it will acquire the class="link current" and toggle the attribute to data-children="visible". Clicking the parent link again will switch the attribute to data-children="hidden," while maintaining the class="link current" for the link.