How to remove document.all from your projects?
Posted on: 2011-11-07
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.
//this
document.all\\[\\"{(.+)}\\"\\]
//to
$(\\'input\\[name="\\1"\\]\\')
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:
document.all\\[\\"{(.+)}\\"\\].value(:b)@={(.+)}; //Search
$(\\'input\\[name="\\1"\\]\\').val(\\2); //Replace
The second one for the getter of the value
[^\\.]document.all\\[\\"{(.+)}\\"\\].value //search
$(\\'input\\[name="\\1"\\]\\').val() //Replace
This is ain't perfect for all situations. Multiple concatenations of document.all
may not be replaced correctly. But, I think it does the job for most of the situation.