Jump to content

What is difference between window.document.getElementById and document.getElementById


klmuralimohan

Recommended Posts

none, it is the same function.document is a global variable, and all global variables can be accessed through the window object.
In other words. document is a variable in window. It can be access like any other object variable
MyObject.myVariable.doSomething()

All of windows variables are also treated like global variables. So you are always in the scope of window.

MyObject = { ... };// In the global/window scope// These are both validwindow.MyObject;MyObject;

Using window before any variable is redundant but it would be courteous to other developers as they could see instantly where the variable you're using is coming from instead going back through your script to find the origin. But for variables like document (where most people remember) it doesn't really matter.

Link to comment
Share on other sites

technically, since everything is javascript is an object, I believe it would be more precise to say document is a property of window. and window is the implied scope (global) in Javascript which is why it is the same thing to say window.document.getElementById vs document.getElementById

Edited by thescientist
  • Like 1
Link to comment
Share on other sites

To add my input, window is the top-level scope. If you're down inside several function calls (several scopes), and you reference a variable, it looks in the local scope first and then goes up until it get to the topmost scope, which is the window object. If your call stack contains 6 scopes and it finds a variable with that name in the third scope up then it will use that one, it uses whatever existing variable it finds on the way up through the stack. If it gets to window and doesn't find the variable then it issues the undefined variable error.

technically, since everything is javascript is an object, I believe it would be more precise to say document is a property of window.
It's also true to say that there aren't really any standalone variables in Javascript, only properties of objects. Every global variable you make is actually a property of the window object, every variable you make in another scope is a property of the scope that you're in. So every variable is actually a property on some scope object, and every function is a method.
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...