🔊 I'm running ffconf: UK's best JS & webdev conf. Find out more & get tickets 📢

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.

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(); }

Posted 10-Feb 2007 under bug & code & getelementbyid & ie & ie6 & ie7.

I am Remy Sharp

I'm a JavaScript developer working professionally on the web since 1999. I run my own consultancy, build products, run training, speak at conferences and curate the UK's best JavaScript event.

Subscribe

Posts, web tech insights, exclusive workshop and training discounts and more, direct to your inbox.

Comments