11

i have the following index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript">
        </script>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                console.log(foo); // jQuery assumes foo is an id?
            });
        </script>
    </head>
    <body>
        <div id="foo">i'm a div</div>
    </body>
</html>

the console outputs:

<div id="foo">i'm a div</div>

why?

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
mzmm56
  • 1,264
  • 1
  • 14
  • 21

3 Answers3

7

This has got nothing to do with jQuery.

This is because named elements(elements with an ID or name attribute) become properties of the window object.

console.log(foo) is identical to console.log(window.foo);

Since your div is a named element(id="foo"), it is added to window.

Named access on window

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
2

It's not a jQuery behavior, it's (originally) an Internet Explorer behavior. IE has always created global variables for each DOM element that has an id attribute. The variable is named after the id and references the DOM element. Lately, other browsers have been following suit.

pete
  • 24,141
  • 4
  • 37
  • 51
0

JQuery doesn't assume that, but rather JavaScript does. Your foo is unquoted, so it must either be an identifier or undefined. The element with id foo happens to be in the scope of your script, so the element identified by it is logged.

If you renamed it to bar, then you'd be able to reference bar as it'd be a top-level id.

Note that such usage is frowned upon because it is unclear what you're doing in the code without referencing the html. Using document.getElementById(...) or a variant thereof is generally preferred because it is clear what you're doing.

J David Smith
  • 4,780
  • 1
  • 19
  • 24