Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <div id="dontainer">
- <ul>
- <li>1</li>
- <li>2</li>
- <li id="xelement">3</li>
- <li>4</li>
- <li>5</li>
- </ul>
- </div>
- function depth(parent, descendant) {
- var depth = 0;
- var el = $(descendant);
- var p = $(parent)[0];
- while (el[0] != p) {
- depth++;
- el = el.parent();
- }
- return depth;
- }
- // Example call:
- depth(".mainContent", "li")
- function depth(parent, descendant) {
- var depth = 0;
- while (!descendant.isEqualNode(parent)) {
- depth++;
- descendant = descendant.parentElement;
- }
- return depth;
- }
- // Example call:
- depth(document.querySelector('.mainContent'), document.querySelector('li'))
- $.fn.depth = function() {
- return $(this).parents().length;
- };
- function countDepth(node, stopPredicate, count) {
- count = count || 0
- stopPredicate = stopPredicate || function () {}
- if (stopPredicate(node) || !node.parentNode) {
- return count
- }
- return countDepth(node.parentNode, stopPredicate, count + 1)
- }
- var depth = countDepth(document.getElementById("xelement"), function (node) {
- return "dontainer" == node.id
- })
- // or, with no predicate -- will count *full* depth
- // depth = countDepth(document.getElementById("xelement"))
- alert(depth)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement