Skip to content

Commit 95639e7

Browse files
committed
Corresponding node in two identical DOM trees
1 parent f00ccf5 commit 95639e7

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

challenges/DOM.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
1. [Show the different ways of selecting an element from DOM](#Q1)
88
1. [Show the ways to loop over the Nodelist obtained after querying for the elements](#Q2)
99
3. [Design and Implement a Node Store, which supports DOM element as key](#Q3)
10+
4. [Implement a function to find the closest ancestor with the provided selector](#Q4)
11+
5. [Write a function to find the corresponding node in two identical DOM trees](#Q5)
1012

1113
---
1214

@@ -112,5 +114,58 @@ Element.prototype.closest = function(selector) {
112114

113115
<br />
114116

117+
#### Q5
118+
### Write a function to find the corresponding node in two identical DOM trees
119+
120+
- Given two same DOM tree A, B, and an Element a in A, find the corresponding Element b in B. By corresponding, we mean a and b have the same relative position to their DOM tree root.
121+
122+
```js
123+
const A = document.createElement('div')
124+
A.innerHTML = `
125+
<div>
126+
<div>
127+
<div>
128+
<div id="node1"></div>
129+
</div>
130+
<div>
131+
</div>
132+
<div>
133+
<div>
134+
<p id="node2"></p>
135+
</div>
136+
</div>
137+
<div>
138+
</div>`
139+
140+
141+
const B = A.cloneNode(true)
142+
const node1 = A.querySelector('#node1')
143+
const node2 = A.querySelector('#node2')
144+
const node1Target = B.querySelector('#node1')
145+
const node2Target = B.querySelector('#node2')
146+
147+
findCorrespondingNode(A, B, node1) // node1Target
148+
findCorrespondingNode(A, B, node2) // node2Target
149+
```
150+
151+
```js
152+
const findCorrespondingNode = (rootA, rootB, target) => {
153+
if(rootA === target) return rootB;
154+
155+
if(rootA.childElementCount) {
156+
for(let i = 0; i < rootA.childElementCount; i++) {
157+
let result = findCorrespondingNode(rootA.children[i], rootB.children[i], target);
158+
if(result) {
159+
return result
160+
}
161+
}
162+
}
163+
}
164+
```
165+
166+
###### References
167+
- https://bigfrontend.dev/problem/find-corresponding-node-in-two-identical-DOM-tree
168+
169+
<br />
115170

116171
[[] Back to top](#home)

0 commit comments

Comments
 (0)