Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference between window.element and element while accessing DOM elements

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"?

like image 239
anandharshan Avatar asked Jul 03 '17 07:07

anandharshan


People also ask

What is the difference between window and document object in JavaScript?

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.

How do you access elements using DOM?

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.


1 Answers

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.

like image 173
Rory McCrossan Avatar answered Oct 10 '22 11:10

Rory McCrossan