I like understand how browser differentiates between hello and window.hello in below-given code
http://jsfiddle.net/PH3t2/291/
var hello = "new hello";
console.log("variable hello : " + hello); // <-- prints "new hello"
console.log(window.hello); // <-- logs HTML elements
<div class="mainWrapper">
<div class="mainBox" id="hello">
main
</div>
<div class="clear" id="hello"></div>
</div>
How does specified window print HTML elements rather than the string "new hello"
?
window is the execution context and global object for that context's JavaScript. document contains the DOM, initialized by parsing HTML. screen describes the physical display's full screen.
The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.
The issue is because by default the browser stores all elements as properties of the window
keyed by their id
attribute - this is part of the reason you cannot have multiple elements with the same id
, which is why the HTML you've shown is invalid.
It's also why window.hello
returns an Element object - it's a reference to the first <div>
in your HTML.
Similarly, the browser knows that when you define the hello
variable you want a value stored separately from the reference it has to the window.hello
element. This is why hello
returns the "new hello"
string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With