Site Navigation

Saturday, August 4, 2007

DOM Method Support - What dreams are made of...

In the ideal world, each and every browser would support these properly, and development would be a breeze... but alas, that is not the case.

For each method listed below, I'll link to the various bugs in terms of their implementation.

getElementById( id )

What seems like the most simplistic method available, yet also one of the most powerful, is unfortunately broken. (bug 152) describes how Internet Explorer, will return an element, if it matches by the id attribute as designed, but will also return a match based on the name attribute. It will also disregard your case-sensitive searches and return elements with IDs with non-matching case (bug 154).

createElement( type )

Another super simple, but super useful method, is again plagued with issues. The correct syntax is:


var myDiv = document.createElement( 'div' );
//or
var myHeader = document.createElement( 'h2' );
//or
var myTextBox = document.createElement( 'input' );


Well, lets say you are building up some form elements on-the-fly (very common in today's Web 2.0 world). Say you want to add a hidden field named "showOption" that you will pre-populate with the value "messages", just before the form is submitted to take the user directly to a certain screen.

The code would look something like this:
development would be a breeze... but alas, that is not the case.


var hiddenOption = document.createElement( 'input' );
hiddenOption.setAttribute('name', 'showOption');
hiddenOption.setAttribute('value', 'messages');
hiddenOption.setAttribute('type', 'hidden');
var myForm = document.forms[0];
document.appendChild(hiddenOption, myForm);
myForm.submit();


So as long as you have a form, this should work! Well, not in Internet Explorer!

As it turns out, in (bug 235) Internet Explorer, you can't set the name attribute on an Element... any Element! To overcome this, there is a hack, which explains why the createElement method is broken (bug 124) in IE. To make the above code snippet work in IE, you need to do this:


var hiddenOption = document.createElement( '<input name="showOption">' );
hiddenOption.setAttribute('type', 'hidden');
hiddenOption.setAttribute('value', 'messages');
var myForm = document.forms[0];
document.appendChild(hiddenOption, myForm);
myForm.submit();


Did you spot the changes?

Change#1.) The Element we create is a string that is the HTML tag, with the name attribute. This is not only quite ugly (mixing tags in strings), but also completely against the spec! document.createElement Spec Reference.

Change#2.) We moved the "type" attribute up to be the first attribute set. The reason for this, is that in IE you can't change the type attribute (bug 237) after the node is added to the DOM, and the default type is always "text". In this code snippet, it didn't matter, but if we had added this to the DOM, before setting the type, we would have been stuck.