File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 12
12
6 . [ Write a function to get depth of a given DOM tree] ( #Q6 )
13
13
7 . [ Implement a function to get the root node of a given DOM fragment] ( #Q7 )
14
14
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 )
15
16
16
17
---
17
18
@@ -295,4 +296,34 @@ function getElementsByTagName(root, tagName) {
295
296
- https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
296
297
297
298
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
+
298
329
[[ ↑] Back to top] ( #home )
You can’t perform that action at this time.
0 commit comments