JS/jQuery: Get depth of element?

后端 未结 6 2138
面向向阳花
面向向阳花 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:42

    function elementDepth(el){
    	var depth = 0
    	while(null!==el.parentElement){
    		el = el.parentElement
    		depth++
    	}
    	return depth
    }
    console.log(elementDepth(document.getElementById('test')))
    Hi

    It says 3 in this example because it counts the outer

    , the and the tag.

提交回复
热议问题