6

Possible Duplicate:
document.all vs. document.getElementById

I'm refactoring some old code written by somebody else. And I came across the following snippet:

if (document.all || document.getElementById) {
   ...
}

When will the code within the if-statement be executed?

Thank you!

Community
  • 1
  • 1
Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 1
    Read this question and answer: http://stackoverflow.com/questions/2408424/document-all-vs-document-getelementbyid – Mario S Dec 01 '12 at 19:43
  • Using **`document.all`** and **`document.getElementById`** without any parameters will return "true" if it is supported in that browser. So, your "if" will be executed if **`document.all`** is supported: `"IE 4 -> 10"`, some versions of `Opera`, and perhaps others; **Or** if **`document.getElementById`** is supported: `"IE 5 and up"`, `"Netscape 6 and up"`, and probably all modern versions of "Firefox", "Chrome", "Safari", etc. The "if" will ***not*** execute for `"IE < 4"`, `"Netscape < 6"`, and some very old versions of most other browsers. – Kevin Fegan Feb 17 '14 at 23:58
  • Actually, that is false. Nowadays, `document.all` is falsey for backwards compatibility reasons, despite still being an object. For example, running `console.log(!!document.all, document.all.length)` prints out `false 1059` for me. – Antimony Aug 22 '17 at 01:05

1 Answers1

8

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 has a unique id on the document.

Nikola
  • 14,888
  • 21
  • 101
  • 165
  • 2
    Linking to other answers should be done in comments, except in circumstances when you are answering something very different and adding as a reference – Michael Berkowski Dec 01 '12 at 19:45
  • Thank you for your answer. But when exactly will the code within the if-statement be executed? In my case both `document.all` and `document.getElementById` don't have any parameters like `div1`. – Evgenij Reznik Dec 01 '12 at 21:44
  • @user1170330: If I understand right, it will be executed if the user has JavaScript turned "on" in his browser. Also, as I've read [here](http://javascript.about.com/od/hintsandtips/a/worst_4.htm) it seems this first if case was for IE4. So, you could kick that if out of your code and use something other to check if user has JS enabled in his browser (like – Nikola Dec 02 '12 at 00:40
  • 1
    @Nikola: So, when does the `else` branch get run, exactly? – SamB Aug 31 '16 at 22:24
  • @SamB In old versions of Netscape. – JustinCB Jul 12 '18 at 18:14