-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindDomNode.html
More file actions
76 lines (71 loc) · 2.48 KB
/
Copy pathFindDomNode.html
File metadata and controls
76 lines (71 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<html>
<head></head>
<body>
<div>
<div id="dom1">
<div></div>
<div></div>
<div>
<div>
<div></div>
</div>
<div>
<div id="node1">This is the node</div>
<div></div>
</div>
</div>
<div>
<div></div>
</div>
</div>
<div id="dom2">
<div></div>
<div></div>
<div>
<div>
<div></div>
</div>
<div>
<div>This is the other node</div>
<div></div>
</div>
</div>
<div>
<div></div>
</div>
</div>
</div>
<script type="text/javascript">
var tree1 = document.getElementById("dom1"),
tree2 = document.getElementById("dom2"),
node1 = document.getElementById("node1");
// NodeList.prototype.indexOf = function (item) {
// return Array.prototype.indexOf.call(this, item);
// };
//build a ref tree that contains the parent index
function getPaths (childNode, baseNode, res) {
res = res || [];
if(childNode !== baseNode) {
var parentNode = childNode.parentNode;
if(parentNode) {
var index = Array.prototype.indexOf.call(parentNode.childNodes, childNode);
res.push(index);
return getPaths(parentNode, baseNode, res);
}
}
return res;
}
function getChildNodeFromParentTree (parentNode, treePaths) {
var index = treePaths.pop();
var childNode = parentNode.childNodes[index];
if(treePaths.length > 0) {
return getChildNodeFromParentTree(childNode, treePaths);
} else {
return childNode;
}
}
var otherNode = getChildNodeFromParentTree(tree2, getPaths(node1, tree1));
console.log("The node is: ", otherNode);
</script>
</body>
</html>