The JavaScript function document.getElementById(), long a staple in the front-end web development community, seems pretty straightforward. Unless you’re maintaining an application that uses a legacy Internet Explorer document mode. I found this out the hard way when debugging a legacy application that had been running in IE 5 quirks document mode. After wrapping the legacy application in a modern front-end and making incremental modernization updates, I started seeing document.getElementById() explode with JavaScript errors. After an extensive, failed search of the legacy source code for any elements with the id in question, I turned to the web for help.
The verdict? getElementById() has inconsistent behavior in IE7 and prior document modes. Instead of searching for an element by ID, Microsoft programmers of old broke with the specification and had Internet Explorer return the first element with the matching ID or Name property.
<div name="MyElement" id="SomethingElse"></div> <div id="result"></div> |
<script> var id = "MyElement"; var element = document.getElementById(id); if(element) document.getElementById("result").innerHTML = "Found element with id of " + id + "."; else document.getElementById("result").innerHTML = "Element with id of " + id + " was not found!"; </script> |
When running the above code a modern browser or IE8+ document mode, the result will be what you probably expect: Element with id of MyElement was not found!
However, you’ll be greeted with the following unexpected result when running in IE7 document mode or below: Found element with id of MyElement.