7

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

laksys
  • 3,228
  • 4
  • 27
  • 38

3 Answers3

17

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

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • 1
    Btw, using `document.querySelectorAll('[id]')` instead of the `*` will reduce the search space considerably. In the fiddle it goes from 14 elements to only 3. – tiffon Dec 17 '12 at 16:56
2

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)
David Avsajanishvili
  • 7,678
  • 2
  • 22
  • 24
0

I think that what you really need is to in fact check if that id or namespace is already taken, before using it rather than check if you've made a mistake after you've made it...

I've written this function long before around the year 2006.Probably earlier It checks whether that id is already taken.

( It does a lot more but this is it's most elemental use )

function isNS( arg, f ) { 
    if(typeof arg!="string")throw( 'TYPE_ERROR:"string required"');

    var i, a = arg.split("."), c = this, s = [], b, r;
    f = f || 0;
    
    for( i in a ) {
        c ? a[i] in c ? ( c = c[ a[i] ], s.push( a[i] ), b = !0 ) : 
    b = !1 : 0;
    }
        r = [ b, c, s, a, arg ];
        return f < 0 ? r : r[+f||f]; 
 }
 ;
 console.log( isNS("par") )
<p id=par>Paragraf with id "par"
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26