IE 7 breaks getElementById

(edit)

First let me say this took me ages to work out how this was going wrong, and that this bug affects both IE6 and IE7.

IE is treating the name attribute on forms as the ID attribute, causing the getElementById to return very unexpected results.

Attend ffconf 2016

The UK's best JS and web development conference. Find out more & get tickets.

See the example of getElementById breaking.

I've not investigated this beyond the FORM element, but the problem is this:

If you have an element whose ID is 'container', and a form whose name is 'container' but ID is anything else, say: 'formContainer', running the following:

var elm = document.getElementById('container') elm.style.display = 'none';

In IE only, the form will disappear. Correctly in all other browsers, the element whose ID is container will disappear.

I can only assume this harks back to when the name attribute was being used as the identify, but has now been formally depreciated by W3 (for XHTML) and only around for backward compatibility.

The solution is simply not to use the name attribute on forms. You can still easily target the form without it:

document.getElementById('submitButton').onclick = function() { // do some code this.form.submit(); }

Want more?

Posts, web development learnings & insights, exclusive workshop and training discounts and more, direct to your inbox.

Comments