Tree using ul li and javascript without plugin

I am trying to create a simple tree using javascript without a plugin in here
Here is my html

<ul class="tree">
    <li>First Child
        <ul>
            <li>First Child
                <ul>
                    <li>First Child</li>
                    <li>Second Child</li>
                    <li>Third Child</li>
                    <li>Fourth Child</li>
                </ul>
            </li>
            <li>Second Child</li>
            <li>Third Child</li>
            <li>Fourth Child</li>
        </ul>
    </li>
    <li>Second Child</li>
    <li>Third Child</li>
    <li>Fourth Child</li>
</ul>

and my js

$( "li" ).on( "click", function() {
    if ($(this).children('ul').css('display') == 'none') {
        $(this).children('ul').css("display", "");
    } else {
        //alert( $( this ).text() );
        $(this).children('ul').css("display", "none");
    }
});

but it only works with the first level. How to do it.

+4
source share
1 answer

The bubble event occurs there. use e.stopPropagation()to block it. And by the way, you do not need to change / check the display property so that any element is visible / hidden, just use    .toggle().

Try

$("li").on("click", function (e) {
    e.stopPropagation();
    $(this).children('ul').toggle();       
});

Demo

+5
source

Source: https://habr.com/ru/post/1534033/


All Articles