JS/jQuery: Get depth of element?

后端 未结 6 2067
面向向阳花
面向向阳花 2020-12-29 07:21

What\'s the easiest way to get the depth of an element in pure JavaScript or jQuery? By \"depth\" I mean how many elements deep is it nested, or how many ancestors does it h

相关标签:
6条回答
  • 2020-12-29 07:33

    My advice would be to rethink the way you are solving your problem - I think finding the number of generations between nodes probably isn't the best way to go, it sounds like a solution that will be likely to break easily by future changes to the code.

    If you insist however, the solution (by Cletus, in native javascript) seems pretty good on this page: find number of nodes between two elements with jquery?

    0 讨论(0)
  • 2020-12-29 07:35

    An additional note. If you want to get the depth relative to a certain context you can do:

    var depth = $("#my-element","#ContextContainerID").parents("ul").length;
    

    Above, I'm searching for how many UL's are within the container #ContextContainerID

    0 讨论(0)
  • 2020-12-29 07:42

    function elementDepth(el){
    	var depth = 0
    	while(null!==el.parentElement){
    		el = el.parentElement
    		depth++
    	}
    	return depth
    }
    console.log(elementDepth(document.getElementById('test')))
    <div>
      <span id="test">Hi</span>
    </div>

    It says 3 in this example because it counts the outer <div>, the <body> and the <html> tag.

    0 讨论(0)
  • 2020-12-29 07:51

    How about:

    $('#my-element').parents().length
    
    0 讨论(0)
  • 2020-12-29 07:52

    Supposing you don't want to include body and html tag in the parents to count use:

    $("#element").parents("*").not("body,html").size()
    

    Online demo here: http://jsfiddle.net/zaJff/

    0 讨论(0)
  • 2020-12-29 07:55

    Try something like this:

    <html>
        <head>
            <title>MooExample</title>
            <script type="text/javascript" src="jquery.js"></script>
            <script type="text/javascript">
                $(document).ready(function() {
                    $("li").click(function() {
                        alert($(this).parents().length);
                    });
                });
            </script>
        </head>
    
        <body>
            <ul>
                <li>moo</li>
                <li>foo</li>
                <li>fasoo</li>
                <li>moasf</li>
                <li>moosadg</li>
                <li>moo1</li>
                <li>moo412</li>
                <li>moo613a</li>
            </ul>
        </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题