Simple Method for Finding a parent node in js _ javascript skills

Source: Internet
Author: User
The method for finding the code of the parent node implemented by javascript is good.


Title


  • Project 1


    • Subclass 1

    • Subclass 2


  • Project 1

  • Project



In the code above, when you click a project or subclass, the parameters are the same because the trigger event is the same, which can distinguish whether the user clicks "Project x" or "subclass x ", except this. innerHTML can be used to determine whether they are inside the text.
    The element is the vertical position (node depth) in the xml document of the root node. For example, in Project 1
      The node depth in is 2, and the node depth of "subclass 1" is 4.

      After eliminating the recursive method, the depth of the computing node finds 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(n1_1_document.doc umentElement) {return-1;} // The target parent node cannot be found to prevent endless loops.
      }
      }
      The Return Value of the function is an index number. If the entry node is the same as the queried parent node (that is, the same element), the return value is 0. After the parent node is found in the upstream loop, the node level is returned, if you find the root node of the entire page, for example, if you still cannot find it,-1 is returned and the loop ends.

      The returned value is similar to the built-in indexOf method of the String object. The key to the function is the second for parameter n = n. parentNode, Which is clever.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.