File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 12126 . [ Write a function to get depth of a given DOM tree] ( #Q6 )
13137 . [ Implement a function to get the root node of a given DOM fragment] ( #Q7 )
14148 . [ 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 )
You can’t perform that action at this time.
0 commit comments