Getting duplicate ids in an HTML document

I needed a way to identify all HTML elements with duplicate IDs. This is a seemingly simple task, but unfortunately, I didn't find anything out there that fit the bill.

I did find a couple functions that returned the duplicates, but they didn't include the first occurrence (I guess they assume the first occurrence isn't a duplicate, but all subsequent occurrences are).

So here's a function that does the job.

function getAllDuplicateIds() {  
  const elements = [...document.querySelectorAll('[id]')];  
  const ids = elements.map(el => el.id);  
  const dups = elements.filter(el => ids.filter(id => id === el.id).length > 1);  
  
  return dups;  
}

This function will return an array of elements in the document that have duplicate IDs. If no duplicates are found, an empty array is returned.

If you only need all occurrences after the first, here's a similar ES6 function for that, too.

function getDuplicateIds() {  
 const elements = [...document.querySelectorAll('[id]')];  
 const ids = [];  
 const dups = [];  
   
 elements.map(el => ids.includes(el.id) ? dups.push(el) : ids.push(el.id));  
   
 return dups;  
}