find number of nodes between two elements with jquery?

后端 未结 2 538
名媛妹妹
名媛妹妹 2020-12-12 03:13

I\'m having a little trouble figuring out a fast way to accomplish a (seemingly) simple task. Say I have the following html:

  • One
相关标签:
2条回答
  • 2020-12-12 03:46

    If you just want to get to the parent, do this:

    child.parents("#parent");
    

    That's easier than doing:

    child.parent().parent().parent();
    

    Or is there some other reason you need to know the number?

    A simple loop could do it:

    var node = child[0];
    var depth = 0;
    while (node.id != 'parent') {
      node = node.parentNode;
      depth++;
    }
    
    0 讨论(0)
  • 2020-12-12 03:48

    Try the closest() function

    http://docs.jquery.com/Traversing/closest#expr

    This will give you the total number of ul parents:

    var numofuls = $(this).parents('ul').length;

    0 讨论(0)
提交回复
热议问题