How to check the tags that contains duplicate ids in javascript?
Try this:
var nodes = document.querySelectorAll('[id]');
var ids = {};
var totalNodes = nodes.length;
for(var i=0; i<totalNodes; i++) {
var currentId = nodes[i].id ? nodes[i].id : "undefined";
if(isNaN(ids[currentId])) {
ids[currentId] = 0;
}
ids[currentId]++;
}
console.log(ids);
http://jsfiddle.net/sekVp/1
Here is a shorter way to achieve the same as the approved answer (count occurrences of IDs):
const ids = Array.from(document.querySelectorAll('[id]'))
.map(v => v.id)
.reduce((acc, v) => { acc[v] = (acc[v] || 0) + 1; return acc }, {});
console.log(ids);
If only list of duplicate IDs is needed, the entries can be filtered:
Object.entries(ids)
.filter(([key, value]) => value > 1)
.map(([ key, value]) => key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With