Pregunta

I'm working on a cross-browser compatibility upgrade for a website, and have run into a very interesting issue.

The current JavaScript uses document.all("whatever").value to access the value of hidden inputs, textboxes, checkboxes, etc.

I have read articles and posts that state that document.all("") does NOT work in Firefox/Chrome, use document.getElementById("") instead as this is the standard across all browsers.

So, I decided to test our current website and debugged through the JavaScript and saw that document.all was in fact UNDEFINED and could not pull the value it was trying to access...cool right?

Well, I wrote a simple HTML page JUST to do a simple test on this. I created an input of type text and put:

    <input id="testinput" name="testinput" type="textbox" value="5" />

Then my JavaScript call looks like:

    alert(document.all("testinput").value);

The result? The value showed up in the alert every time, on every browser. Even more interesting, when I debugged the JavaScript, I typed in the command window (chrome) document.all, and the output was undefined...but document.all("testinput").value had an output of 5.

Is there something I am missing here?

Does document.all actually work in modern browsers but just not recommended? I'm hoping somebody can shed some light on this, because this replacement would entail a lot of code being changed.

¿Fue útil?

Solución

Yes. that's exactly how it works.

The problem is that some legacy web pages test for document.all as a way of checking for IE. The JS code then has two code paths: one for IE and one for other browsers. Other legacy pages however, use document.all blindly assuming that it only needs to work with IE, because it was created at a time when IE was the overwhelmingly popular browser in use.

Since the latter pages would simply break in non-IE browsers, which is not good for the market share or reputation of those browsers, they implement document.all() to cope with them. But because in the former case they want the JS code to follow the non-IE code path, for document.all itself (and several other similar way of testing for the presence of document.all) they return "undefined".

For the details, see The HTMLAllCollection interface and The [[IsHTMLDDA]] Internal Slot

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top