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 an ES6 function that does the job.

function getAllDuplicateIds() {
const elements = [...document.querySelectorAll('[id]')];
const ids = =>;
const dups = elements.filter(el => ids.filter(id => id === > 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 = []; => ids.includes( ? dups.push(el) : ids.push(;

return dups;
Author avatar

About the author

Creator of Surreal CMS, Postleaf, and other web things.

Need to get in touch? Catch me on Twitter.