Skip to content

Commit 551bf30

Browse files
committed
Check duplicate IDs in DOM tree
1 parent 550c74c commit 551bf30

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

challenges/DOM.md

+31
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
6. [Write a function to get depth of a given DOM tree](#Q6)
1313
7. [Implement a function to get the root node of a given DOM fragment](#Q7)
1414
8. [Implement a function to get unique tag names in a given DOM tree](#Q8)
15+
9. [Implement a function to check if a given DOM tree has duplicate IDs](#Q9)
1516

1617
---
1718

@@ -295,4 +296,34 @@ function getElementsByTagName(root, tagName) {
295296
- https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
296297

297298

299+
#### Q9
300+
### Implement a function to check if a given DOM tree has duplicate IDs
301+
302+
- In a given DOM tree, the id on each node has be unique
303+
- Although HTML is very forgiving, but we should avoid duplicate identifiers
304+
305+
```js
306+
/**
307+
* @param {HTMLElement | null} tree
308+
* @return {Boolean}
309+
*/
310+
function hasDuplicateId(tree, idSet = new Set()) {
311+
if(!tree) return false;
312+
313+
if(idSet.has(tree.id)) return true;
314+
315+
tree.id && idSet.add(tree.id);
316+
317+
if(tree.hasChildNodes()) {
318+
for(let child of tree.children) {
319+
const result = hasDuplicateId(child, idSet);
320+
if(result) return true;
321+
}
322+
}
323+
324+
return false;
325+
}
326+
```
327+
328+
298329
[[] Back to top](#home)

0 commit comments

Comments
 (0)