1

I was playing with javascript, and I don't understand how this little snippet can works:

html > <div id="foo_bar"></div>

javascript > foo_bar.textContent = "Hello, world!";

result > <div id="foo_bar">Hello, world!</div>

foo_bar is not a variable defined before in the code. I only have this one line in my javascript code.
Check the jsFiddle demo : http://jsfiddle.net/6W25e/

So what really happend?
I always thought that was impossible to access dom elements without dom methods like element.getElementById(). Is there any documentation on this behavior? (my searches have been unsuccessful on mdn)

Vincent
  • 13
  • 2

1 Answers1

0

Taken from bobInce

What is supposed to happen is that ‘named elements’ are added as apparent properties of the document object. This is a really bad idea, as it allows element names to clash with real properties of document.

IE made the situation worse by also adding named elements as properties of the window object. This is doubly bad in that now you have to avoid naming your elements after any member of either the document or the window object you (or any other library code in your project) might want to use.

Read more: Do DOM tree elements with ids become global variables?

This means it's very bad practice to do that, and some browsers don't support it, the good ones that don't fall into the trick.

What happens is that some browsers will make them global variables as classes of window, making them immediately accessible when the window loads.

Community
  • 1
  • 1
Cilan
  • 13,101
  • 3
  • 34
  • 51