views:

364

answers:

3

When should you use document.all vs. document.getElementById

What is your answer?

+4  A: 

document.all is a proprietary Microsoft extension to the W3C-standard. getElementById is standard - use that.

Evaluate if using a js library like jquery would come in handy :)

$("#id") is the jquery equivalent for getElementById. PLUS, you can use more than even only css3 selectors.

edit: w3c

henchman
E.g., use `getDocumentById`, there's no longer any reason to use `document.all`
T.J. Crowder
The relevant standard (DOM) is from the W3C, not the ECMA.
T.J. Crowder
Why do you promote jQuery? The same is true for many other libraries, like Prototype or Oz.js (`$("id")`). And why do you revert spelling corrections?
Marcel Korpel
@T.J.Crowder: you meant `getElementById`?
Marcel Korpel
which spelling corrections? you are totally right, this function is available in many more javascript frameworks, though everyone has his favorite :-)
henchman
Strange, look at this: http://stackoverflow.com/posts/2408435/revisions
Marcel Korpel
I don't know what happened here, but i re-corrected your corrections.
henchman
Those were not my corrections, but T.J.'s. But I think what happened: you edited your original answer, while T.J. was correcting it, and you saved your edits after T.J. did. I'll have a look at meta.stackoverflow.com to see if this behaviour can be prevented.
Marcel Korpel
thank you for your help!
henchman
+5  A: 

document.all is very old, you don't have to use it anymore.

To quote Nicholas Zakas:

For instance, when the DOM was young, not all browsers supported getElementById(), and so there was a lot of code that looked like this:

if(document.getElementById){  //DOM
    element = document.getElementById(id);
} else if (document.all) {  //IE
    element = document.all[id];
} else if (document.layers){  //Netscape < 6
    element = document.layers[id];
}
Marcel Korpel
+2  A: 

document.all() is a non-standard way of accessing DOM elements. It's been deprecated from a few browsers. It gives you access to all sub elements on your document.

document.getElementById() is a standard and fully supported. Each element have a unique id on the document.

If you have:

<div id="testing"></div>

Using

document.getElementById("testing"); 

Will have access to that specific div.

Marcos Placona