Home >Web Front-end >JS Tutorial >A simple way to find the parent node in js_javascript skills

A simple way to find the parent node in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:03:261717browse

 Title
 

                                          🎜>
  •                                                  >Sub-category one
  •                                                                                🎜>Project 1

                                                                                   , the parameters are the same, it can distinguish whether the user clicks on "project x" or "subcategory To differentiate by the vertical position (node ​​depth) in the document, for example, the node depth of "Project One" in
    • is 2, and the node depth of "Subcategory One" is 4. calculates the node depth after excluding After the recursive method, I found a simpler method:

    • function parentIndexOf(node,parent){
    • if(node==parent){return 0;} for (var i= 0,n=node; n=n.parentNode; i ){ if(n==parent){return i;}
    • if(n==document.documentElement){return -1;} // The target parent node cannot be found to prevent an infinite loop
      }
    } The return value of the
    function is the index number. If the entry node is the same as the parent node being searched (that is, the same element), the return value is 0. After the upward loop finds the parent node, it returns the number of nodes searched upward. If the upward search reaches the root node of the entire page, such as
  • , and it cannot be found, it returns -1 and ends the loop. The return value is similar to the built-in indexOf method of String object. The key to the function is the second parameter n=n.parentNode of for, which feels clever.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn