TikTaZ
TikTaZ

Reputation: 710

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 :)

Upvotes: 1

Views: 2021

Answers (2)

manish
manish

Reputation: 497

This way seems better.

HTML

<ul>
 <li>
  <input id="btn1" type='button' onclick="displayMenu(event);" />
 </li>
 <li><ul id="page1" style="display: none" class="hide">
  <li>Some text</li>
 </ul></li>
 <li>...</li>
</ul> <

JS

function displayMenu(event) {
    var id = event.target.id.substring(3);
    var ulDisplay = document.getElementById("page" + id);
    ulDisplay.style.display = "block";
}

Upvotes: 0

Scott
Scott

Reputation: 21501

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>

Upvotes: 2

Related Questions