I've found that there are a number of duplicate IDs in the project I'm working on. I don't want to scrape through the entire product all at once, or use on overly heavyweight solution like a full HTML validator - I just want a quick script I can run on any given page to easily identify any duplicate IDs present while I'm working there.
I've found a question along these lines, but it's very old and requests a jQuery solution - we don't use jQuery in this project and it's frankly pretty out of date.
So: what's a little ES6 snippet I can run in the console to identify duplicate IDs in the DOM?
In modern JavasScript (ES6+), without jQuery:
[...document.querySelectorAll('[id]')].forEach(el => {
const dups = document.querySelectorAll(`[id="${el.id}"]`);
if (dups.length > 1 && dups[0] === el) {
console.error(`Duplicate IDs #${el.id}`, ...dups);
}
});
All credit to @Rafi: https://stackoverflow.com/a/62145753/1033203