Topic description
Finds the closest common parent of two nodes, which can include the node itself.
Enter description:
oNode1 and oNode2 are in the same document and will not be the same node.
Code:
1 // Method
12 // oNode.contains(oNode2): The parent node oNode (or itself) contains the child node oNode2, return true
3 // This method is more efficient than the recursive method
4 function commonParentNode(oNode1, oNode2) {
5 while (oNode1){
6 if (oNode1.contains(oNode2)){
7 return oNode1;
8 }
9 oNode1 = oNode1.parentNode;
10 }
11 }
12
13 // Method 2: recursion
14 function commonParentNode(oNode1, oNode2) {
15 if(oNode1.contains(oNode2)){
16 return oNode1;
17 }
18 else {
19 return commonParentNode(oNode1.parentNode,oNode2);
20 }
21 }
22
23 // Method 3: Compare parent nodes
24 function commonParentNode(oNode1, oNode2 ) {
25 // Take the parent node
26 of oNode1 var parent1 = [];
27 parent1.push(oNode1);
28 while (oNode1.parentNode){
29 parent1.push(oNode1.parentNode);
30 oNode1 = oNode1.parentNode;
31 }
32 //取oNode2的父节点
33 var parent2=[];
34 parent2.push(oNode2);
35 while(oNode2.parentNode){
36 parent2.push(oNode2.parentNode);
37 oNode2 = oNode2.parentNode;
38 }
39 //比较
40 var i = 0 , j =0;
41 while(i<parent1.length){
42 j = 0;
43 oNode1 = parent1[i++];
44 while(j<parent2.length){
45 if(oNode1 == parent2[j++]){
46 return oNode1;
47 }
48 }
49 }
50 return null
51 }