How to remove document.all from your projects?<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

How to remove document.all from your projects?

Posted on: November 7, 2011

Recently, I had to work on pages which contained a lot of code that were using the famous Internet Explorer 4 document.all javascript method. It's not supported by all browser and should not be used. You should use unique identifier but I couldn't because time was limited for the change.

We already user JQuery so I knew that I can search by attribute.

The plan was to replace all document.all["XYZ"] to $('input[name="XYZ"]'). As you see, the XYZ change between each files. The solution is with Visual Studio (or other software that do replace with Regex) to use the Replace tool with a Regex expression.

1//this document.all\\[\\"{(.+)}\\"\\] //to $(\\'input\\[name="\\1"\\]\\')

regex 300x400

What it does is that it search for the string document.all["???"] and replace with input[name="???"] and the ??? is replaced with what is found in the search and used in the replacement. This way, the name change every time it founds a new string with document.all.

This can will be good for some situation but not for code like this:

document.all["???"].value because in JQuery the value is get by val() and set by val('new value');

To be able to do this correctly, 2 Replaces is required.

The first one for the setter of the value:

1document.all\\[\\"{(.+)}\\"\\].value(:b)@={(.+)}; //Search $(\\'input\\[name="\\1"\\]\\').val(\\2); //Replace

The second one for the getter of the value

1[^\\.]document.all\\[\\"{(.+)}\\"\\].value //search $(\\'input\\[name="\\1"\\]\\').val() //Replace

This is ain't perfect for all situations. Multiples concatenations of document.all may not be replaced correctly. But, I think it does the job for most of the situation.