I just got a major bug that was really hard to solve and found out after a lot of work it was because two HTML elements had the same ID attribute.
Is there a command that spots double IDs across the whole DOM?
Update:
After reading all the comments I tested the different approaches in a relatively big website (http://www.powtoon.com html5 studio) and here are the results.
Please comment if you have better ways then these two.
Both answers returned the same results, but looks like the querySelectorAll
was indeed faster:
QuerySelectorAll
function getDuplicateIdsUsingQuerySelector(){
const idsOccurances = Array.from(document.querySelectorAll('[id]'))
.map(elem => elem.id)
.reduce((allIDs, id) => {
allIDs[id] = (allIDs[id] || 0) + 1
return allIDs
}, {})
return Object.entries(idsOccurances)
.filter(([id, occurances]) => occurances > 1)
.map(([id]) => id)
}
1.5ms per call on average.
Regex
function getDuplicateIdsUsingRegEx(){
const idRegex = / id=".*?"/ig
const ids = document.body.innerHTML.match(idRegex)
const idsOccurances = ids.reduce((allIDs, id) => {
allIDs[id] = (allIDs[id] || 0) + 1
return allIDs
}, {})
return Object.entries(idsOccurances)
.filter(([id, occurrences]) => occurrences > 1)
.map(([id]) => id.slice(4, -1))
}
5.5ms per call average.