find number of nodes between two elements with jquery?

后端 未结 2 550
名媛妹妹
名媛妹妹 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++;
    }
    

提交回复
热议问题