Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - find number of nodes between two elements with jquery?

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

<ul>
  <li>One</li>
  <li>Two</li>
  <li id='parent'>
    <ul>
      <li>Three</li>
      <li>
        <ul>
          <li>Four</li>
          <li id='child'>Five</li>
        </ul>
      </li>
      <li>Six</li>
    </ul>
  </li>
</ul>

And have the following two elements:

var child = $("#child");
var parent = $("#parent");

In this example, it's clear that:

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

will be the same node as 'parent'. But the list I'm traversing is variable size, so I need to find a way to find out how many '.parent()'s I'll need to go through to get to that parent node. I always know where child and parent are, I just don't know how many 'layers' there are in between.

Is there any built in jQuery method to do something like this, or is my best bet a recursive function that gets the parent, checks if the parent is my desired node, and if not calls itself on its parent?

Edit: I may not have explained myself clearly enough. My problem isn't getting TO the parent, my problem is finding out how many nodes are between the child and parent. In my example above, there are 3 nodes in between child and parent. That's the data I need to find.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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++;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...