Search code examples
javascriptnextsibling

nextSibling ul li ul


i'm not sure but if i understood right js nextSibling focus next node ? So why i get trouble, when i want to select ul in a li ?

    <ul>
<li><input id="btn-page" type=button onclick="displayMenu();" /></li>
    <ul class="hide">
        <li>Some text</li>
    </ul>
    <li>...</li>
   </ul>

And my js function :

    function displayMenu() {
   var idMenu = event.target.id;
   var ulDisplay = document.getElementById(idMenu).nextSibling;
   ulDisplay.style.display = 'block';
}

I think i forgot something but i don't know why. Thanks for help :)


Solution

  • As @andreas pointed out the structure of your HTML is not valid because you can't have a UL as child of a UL. But you can have a UL as a child of LI. So consider updating your HTML in this way. Helper function "Next()" from previous similar answer Hide an element's next sibling with Javascript used to find the UL

    <!DOCTYPE html>
    <html>
        <head>
            <style type="text/css">
                .hide { display: none; }
            </style>
            <title>Title</title>
            <script type="text/javascript">
                function next(elem) {
                    do {
                        elem = elem.nextSibling;
                    } while (elem && elem.nodeType != 1);
                    return elem;                
                }
    
                function displayMenu(id) {
                    var ulDisplay = next(document.getElementById(id));
                    ulDisplay.style.display = 'block';
                }
            </script>
        </head>
        <body>
            <ul>
                <li>
                    <input id="btn-page" value="show" type=button onclick="displayMenu(this.id);" />
                    <ul class="hide"><li>Some text</li></ul>
                </li>
                <li>...</li>
            </ul>
        </body>
    </html>