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)

3
  • What about querySelector?
    – Cilan
    Dec 29, 2013 at 22:38
  • Some browsers will create global variables on the window level referencing the elements in the DOM.
    – adeneo
    Dec 29, 2013 at 22:44
  • @AlexeyLebedev Exact duplicate. I should have searched more. Thanks for the link!
    – Vincent
    Dec 29, 2013 at 22:48

1 Answer 1

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.

1
  • Thanks for the link. I agree about the bad idea point, btw.
    – Vincent
    Dec 29, 2013 at 22:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.