Whispers & Screams
And Other Things

Duplicate element ID's in the DOM

lform_javascript_blog_header_image-1600x1080

Short post today folks since its Friday :)

I've been developing quite a lot lately using Angular JS and React JS as I'm currently heavily involved with a startup preparing to release a new IoT product. The app is pretty complex with heavy calls to the server side database but that's not what we're going to talk about today. 

One of the things that seem very straightforward when you're building small UX is ensuring you have a unique array of element ID's in your DOM at any given time but, as the complexity increases, then so does the difficulty in maintaining a mental map of the DOM you have at any given time, especially if elements of your viewport are loading dynamically via ajax calls or whatever. 

The downside to having a duplicate element ID may not always be immediately apparent as it is not something that will always push an error to the console. This can result in confusing erratic behaviour from your application and often hours can be lost trying to work out what on earth is going on. 

By the time you eventually get to the bottom of the problem you realise that you've wasted hours searching for something that was ultimately such a basic error. 

So anyway, this happened to me once or twice over recent weeks. Our application loads dynamic data via ajax quite frequently and the issue I faced could sometimes be intermittent. The worst-case scenario.

After the dust had settled, I decided to create a tool for myself that I could use to quickly establish the presence or otherwise of duplicate ID's. This is what I came up with. Simply punch this code into the command line on your browser inspector console and hey presto!

var DOMElements = document.getElementsByTagName("*"), DOMIds = {}, duplicateIDs = [];

for (var x = 0, len = DOMElements.length; x < len; ++x) {

  var element = DOMElements[x];

  if (element.id) {

  if (DOMIds[element.id] !== undefined) duplicateIDs.push(element.id);

  DOMIds[element.id] = element.name || element.id;

    }

  }

if (duplicateIDs.length) { console.error("Duplicate ID's:", duplicateIDs);} else { console.log("No Duplicates Detected"); }

Feel free to use and abuse as you see fit. I hope this helps somebody out there save some hair :). Have a fab weekend.

The Joy Of Driving
The Web By Proxy
 

Comments

No comments made yet. Be the first to submit a comment
Already Registered? Login Here
Guest
Saturday, 10 June 2023
If you'd like to register, please fill in the username, password and name fields.