Last active
January 8, 2023 17:44
-
-
Save samrocksc/7d09d4c4f1052b0eb526181e82598ecf to your computer and use it in GitHub Desktop.
deeply-nested-clicks.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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