0

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.

1
  • It is part of the problem; the HTML is invalid. Once that happens, how CSS & JavaScript are going to react is undefined. A ul cannot have a div child nor a button child. You might be lucky and get some agreement among some of the browsers on what they'll do, but next month? Next year? Commented Feb 11, 2021 at 20:20

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.