Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html javascript code that check the duplicate id

How to check the tags that contains duplicate ids in javascript?

like image 530
laksys Avatar asked Dec 17 '12 16:12

laksys


2 Answers

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

like image 109
bfavaretto Avatar answered Oct 27 '22 03:10

bfavaretto


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)
like image 43
David Avsajanishvili Avatar answered Oct 27 '22 05:10

David Avsajanishvili