|
7 | 7 | 1. [Show the different ways of selecting an element from DOM](#Q1) |
8 | 8 | 1. [Show the ways to loop over the Nodelist obtained after querying for the elements](#Q2) |
9 | 9 | 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) |
10 | 12 |
|
11 | 13 | --- |
12 | 14 |
|
@@ -112,5 +114,58 @@ Element.prototype.closest = function(selector) { |
112 | 114 |
|
113 | 115 | <br /> |
114 | 116 |
|
| 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 /> |
115 | 170 |
|
116 | 171 | [[↑] Back to top](#home) |
0 commit comments