Skip to content

Instantly share code, notes, and snippets.

@samrocksc
Last active January 8, 2023 17:44
Show Gist options
  • Save samrocksc/7d09d4c4f1052b0eb526181e82598ecf to your computer and use it in GitHub Desktop.
Save samrocksc/7d09d4c4f1052b0eb526181e82598ecf to your computer and use it in GitHub Desktop.
deeply-nested-clicks.js
<!DOCTYPE html>
<head>
<title>I am a page</title>
<style>
.closed {
display: none;
}
.hide_content>ul {
display: none;
}
</style>
</head>
<body>
<h1 class="header">Click Me</h1>
<ul class="has-children">
<li class="no-children">1. no children</li>
<li class="has-children">2. has children
<!-- that you have absolutely zero control over this ul's classes and it is generated from php -->
<ul class="closed">
<li>1. child 1</li>
<li>2. child 2</li>
</ul>
</li>
<li class="has-children">3. has children
<!-- that you have absolutely zero control over this ul's classes and it is generated from php -->
<ul class="closed">
<li>a. child a</li>
<li>b. child b</li>
</ul>
</li>
<li>4. no children</li>
</ul>
</body>
<script>
const header = document.body.querySelector('.header')
const expandables = document.body.querySelectorAll('.has-children')
const parentList = document.body.querySelector('ul');
header.addEventListener('click', (event) => {
if (parentList.classList.contains('closed')) {
parentList.classList.remove('closed')
} else {
parentList.classList.add('closed')
}
})
const subExpandables = expandables[0].querySelectorAll('li')
debugger;
subExpandables.forEach((li) => {
if (li.classList.contains('has-children')) {
li.addEventListener('click', (event) => {
const subUl = event.target.querySelector('ul')
if (subUl) {
if (subUl.classList.contains('closed')) {
subUl.classList.remove('closed')
} else {
subUl.classList.add('closed')
}
}
})
}
})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment