Checking an HTML page for duplicate IDs using jQuery

At work our testers make use of the ID elements on HTML tags quite frequently and when they’re not unique, it usually causes them issues with testing. To avoid the manual parsing of trying to find duplicate IDs in the page source I looked for (and found) a JavaScript function that loops through each ID found on the page and outputs any duplicates into your console.

This code does require that jQuery is defined on the page you are testing.

javascript:(function () {
  var ids = {};
  var found = false;
  $('[id]').each(function() {
    if (this.id && ids[this.id]) {
      found = true;
      console.warn('Duplicate ID #'+this.id);
    }
    ids[this.id] = 1;
  });
  if (!found) console.log('No duplicate IDs found');
})();

You can copy and paste the entire JavaScript function into a bookmark for quick access.

javascript:(function () { var ids = {}; var found = false; $('[id]').each(function() { if (this.id && ids[this.id]) { found = true; console.warn('Duplicate ID #'+this.id); } ids[this.id] = 1; }); if (!found) console.log('No duplicate IDs found'); })();
Matt Busche's Picture

About Matt Busche

Software Engineer and Wheel of Fortune Expert If this article helped you, please consider buying me a book.

Des Moines, IA https://www.mrbusche.com