When IE4 was in the design phase Microsoft wanted to make clear that you could access all
elements and not only layers and therefore using document.all seemed like a
good idea. There are however some problems with using document.all and one is
that it is not language independent. Not many programming languages allows objects to change
property names at runtime. Other issues with document.all is that it allows you to use
it as a VB array usin document.all("id") instead of document.all["id"].
Another bad idea was to bind the tags method to the all collection.
The standard way to get all elements with a certain tag name is to use the method
getElementsByTagName. The same method can be used to get all elements by using
the special argument "*". The return value of this method is an
HTMLCollection and such a collection allows you to directly look up named items
using the method namedItem(sId) or use a JavaScript field look up using brackets
(all[sID]). The collection also has a method called item that works
the same but takes a number as argument. Normally this collection can be thought of as a normal
JavaScript Array/Object.
We add a getter to the prototype of HTMLDocument as well as
HTMLElement that returns the collection
returned by getElementsByTagName("*"). This collection is extended with a
method called tags that return the collection with the tags of the name
passed along.
var allGetter = function () {
var a = this.getElementsByTagName("*");
var node = this;
a.tags = function (sTagName) {
return node.getElementsByTagName(sTagName);
};
return a;
};
HTMLDocument.prototype.__defineGetter__("all", allGetter);
HTMLElement.prototype.__defineGetter__("all", allGetter);
Notice that this emulation does not allow VB style item lookup using all(sId). An
emulation to support this is possible but it would be too slow to be practical.
To allow Mozilla to use the all collection you need to include the ie emu
file as well as call the emulateAllModel function.
<script type="text/javascript" src="ieemu.js"></script>
<script type="text/javascript">
if (moz) {
emulateAllModel();
}
</script>
First a simple demo that looks up an element by its id and then toggles the color.
function toggleColor() {
if (document.all.demoHeader.style.color == "red")
document.all.demoHeader.style.color = "black";
else
document.all.demoHeader.style.color = "red";
}
Then a more useful example that alerts the text of all H2 tags in the document. (Hmm... maybe not so useful after all.)
function alertH2s() {
var str = "";
var h2s = document.all.tags("H2");
for (var i = 0; i < h2s.length; i++)
str += h2s[i].innerHTML + "\n";
alert(str);
}
Introduction
The power of JS
Event Listeners
Classic Event Handlers
Event Object
InnerHTML Model
Element Model
Document All Model
Current Style Model
???