-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy path68.findCommonParent.html
56 lines (50 loc) · 1.64 KB
/
68.findCommonParent.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>设计一个函数,传入两个 DOM 节点,找出它们的最近的父节点</title>
<body>
<!-- 同级 -->
<div class="el1"></div>
<div class="el2"></div>
<script>
// 设计一个函数,传入两个 DOM 节点,找出它们的最近的父节点
// function findCommonParent($el1, $el2) {
// if ($el1.contains($el2)) {
// return $el1
// } else if ($el2.contains($el1)) {
// return $el2
// } else {
// return findCommonParent($el1.parentNode, $el2)
// }
// }
function findCommonParent2(oNode1, oNode2) {
if (oNode1.contains(oNode2)) {
return oNode1
} else if (oNode2.contains(oNode1)) {
return oNode2
} else {
return findCommonParent(oNode1.parentNode, oNode2)
}
}
function findCommonParent (oNode1, oNode2) {
while (!oNode1.contains(oNode2)) {
oNode1 = oNode1.parentNode
}
return oNode1
}
const $el1 = document.querySelector('.el1')
const $el2 = document.querySelector('.el2')
// 同级
console.log(findCommonParent($el1, $el2))
// 1包含2
console.log(findCommonParent(document.body, $el2))
// 2包含1
console.log(findCommonParent($el2, document.body))
console.log(findCommonParent(document.documentElement, document.body))
</script>
</head>
</body>
</html>