0

I'm a little bit confused. Let say I have the following HTML code:

<div id="foo"></div>

And if I write this:

var bar = foo;
console.log(bar);

Then I will get this as output -- Surprisingly, the DOM element with the "foo" ID:

<div id="foo"></div>    // Chrome
[object HTMLDivElement] // FireFox

Is there any specific reason for this behavior? or there is something wrong with my set up? Anyone else can reproduce this also? If it's a correct behavior, when and how should we use it?

Update

I see that there is a similar question here, but not all of questions have been answered there. The answers I see there are mostly talking about IE-specific things which is not true -- at least now.

JSFiddle

Mahdi
  • 9,247
  • 9
  • 53
  • 74
  • @elclanrs I see that question now, but there answers are a bit poor. I hope I get better ones here. Not all of my questions are answered there also. But thanks for pointing out. – Mahdi Jan 17 '14 at 07:38
  • guys, at least go and read all of the answers there. It's not totally what I was looking for. That's pity to see how fast you just close the question. Seriously, go and read all the answers in the other question. – Mahdi Jan 17 '14 at 07:42

1 Answers1

1

Because every named element becomes the global property of window object.

So if you given an id to an element then you can access it via window object as well

<div id="foo"></div>

for above element you can write this

console.log(foo);

which is equivalent to

console.log(window.foo);
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • Thanks for your answer, I was hoping to get more answers here but it's closed now. Do you have any idea where should someone use it instead of using native DOM methods? Is there any performance related issues regarding this way of accessing DOM elements? Is there any recommendation to avoid this or not? – Mahdi Jan 17 '14 at 07:45
  • 1
    @Mahdi Create a html with a few things id'd / named / class'd as "foo". In your console, type 'foo' and see what it gives you. In mine it gives me an array of all the things named foo. This is at least one reason not to use it; if you have form names with the same names as ids or classes, you're going to run into trouble. It's also browser inconsistent. The above works in chrome, but doesn't seem to work in Firefox. – Obversity Jan 17 '14 at 15:51