The method for finding the code of the parent node implemented by javascript is good.
Title
- Project 1
- 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.