Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. <div id="dontainer">
  2. <ul>
  3. <li>1</li>
  4. <li>2</li>
  5. <li id="xelement">3</li>
  6. <li>4</li>
  7. <li>5</li>
  8. </ul>
  9. </div>
  10.  
  11. function depth(parent, descendant) {
  12. var depth = 0;
  13. var el = $(descendant);
  14. var p = $(parent)[0];
  15. while (el[0] != p) {
  16. depth++;
  17. el = el.parent();
  18. }
  19. return depth;
  20. }
  21.  
  22. // Example call:
  23. depth(".mainContent", "li")
  24.  
  25. function depth(parent, descendant) {
  26. var depth = 0;
  27. while (!descendant.isEqualNode(parent)) {
  28. depth++;
  29. descendant = descendant.parentElement;
  30. }
  31. return depth;
  32. }
  33.  
  34. // Example call:
  35. depth(document.querySelector('.mainContent'), document.querySelector('li'))
  36.  
  37. $.fn.depth = function() {
  38. return $(this).parents().length;
  39. };
  40.  
  41. function countDepth(node, stopPredicate, count) {
  42. count = count || 0
  43. stopPredicate = stopPredicate || function () {}
  44. if (stopPredicate(node) || !node.parentNode) {
  45. return count
  46. }
  47. return countDepth(node.parentNode, stopPredicate, count + 1)
  48. }
  49.  
  50. var depth = countDepth(document.getElementById("xelement"), function (node) {
  51. return "dontainer" == node.id
  52. })
  53.  
  54. // or, with no predicate -- will count *full* depth
  55. // depth = countDepth(document.getElementById("xelement"))
  56.  
  57. alert(depth)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement