6

Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?

I am currently working on a mobile site using jquery mobile and I noticed something interesting (to me anyway, as I am still new to js). Inside a function, you can reference an element with just the id.

This is the test code I used (on chrome 22.0.x, firefox 16.0.1, and safari 5.1.7):

<!DOCTYPE html>
<html>
  <head></head>
  <body onload="tt()">
    <div id="abc">Test</div>
    <a id="cba">Test2</a>
  </body>
  <Script>
    function tt() {
        console.log(abc);
        abc.style.backgroundColor = "red";
        return cba;
    }
  </Script>
</html>

No getElementById, no jquery selector, just the id. Has it always been this way? If so, is this a good practice and why does this work? I am thinking function must have a context, but where is it, is it the page?

Any insight would be appreciated, Thanks.

Community
  • 1
  • 1
user1736525
  • 1,119
  • 1
  • 10
  • 15

1 Answers1

8

You are really doing:

window.abc;

This is something that IE started that was really a poor design choice.

See this great answer to a very very similar question

It's really a duplicate but the title does not reflect this.

Try this line in your console to see what I mean.

(function(){ console.log(this); })(); // logs the Window object
Community
  • 1
  • 1
Kyle
  • 21,978
  • 2
  • 60
  • 61