Friday, January 30, 2015

Finding elements with duplicate element IDs on a page

I know - IDs on a page should be unique. That's absolutely right! But have you seen the browser spitting a message that you duplicated one? No? Here's a piece of JavaScript code that'll check your DOM for duplicate IDs:

var elements = document.getElementsByTagName("*"); for (i = 0; i < elements.length; i++) if (elements[i].id != "") for (j = 0; j < i; j++) if (elements[i].id == elements[j].id) { console.log("duplicate id: " + elements[j].id + "; idx " + i + " and " + j); break; }

and now formatted:

var elements = document.getElementsByTagName("*");
for (i = 0; i < elements.length; i++) {
  if (elements[i].id != "") {
    for (j = 0; j < i; j++) {
      if (elements[i].id == elements[j].id) {
        console.log("duplicate id: " + elements[j].id + "; idx " + i + " and " + j); 
        break; 
      }
    }
  }
}

It'll make a list of all the elements in a page, iterate over elements with ID and search for a duplicate entry reporting using console.log so you need to have a fairly modern browser to be using it (I mean ancient IE will not work)

Have fun!


No comments: