Reputation: 15
I have a dropdown navigation on my site
<ul>
<li><a href="index.html">Homepage</a></li>
<li><a href="#">Forum</a></li>
<div class="dropdown">
<button onclick="mainDropdown()" class="mainDropdown">Videos</button>
<ul class="dropdownList" id="dropdownList">
<button id="intro">Introduction</button>
<button id="start">Getting Started</button>
</ul>
</div>
<li class="test"><a href="index.html">Contact</a></li>
</ul>
I have this in my html the UL around everything can be ignored as that isn't a part of the problem nor are the top two LIs
The problem I'm having is with the dropdown division.
function mainDropdown() {
var dropdown = document.getElementById("dropdownList");
dropdown.classList.toggle("active");
if(dropdown.classList.contains("active")) {
document.getElementById("intro").style.display = "block";
document.getElementById("start").style.display = "block";
} else if(!dropdown.classList.contains("active")) {
setTimeout(() => {
document.getElementById("intro").style.display = "none";
document.getElementById("start").style.display = "none";
}, 300);
}
}
This is the javascript method (vanilla, trying to not use JQuery in this project, just as a heads up). This works fine - however, I'm looking for a better way to do this. because when I come to add more sections then the javascript method is going to get quite lengthy.
Is there a method I can use to get the children of the dropdownList UL so I can loop through them and set their display? Instead of adding a bunch of the same line.
Upvotes: 0
Views: 53
Reputation: 27245
Is there a method I can use to get the children of the dropdownList UL so I can loop through them and set their display?
You could get the list of items via querySelectorAll('#dropdownList > *')
.
Or you could use a css selector to toggle the display:
#dropdownList {
display: none;
}
#dropdownList.active {
display: block;
}
Or if you need to do individual items for some reason:
#dropdownList > * {
display: none;
}
#dropdownList.active > * {
display: block;
}
Upvotes: 1