Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery assumes element id? normal behaviour? [duplicate]

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?

like image 350
mzmm56 Avatar asked Oct 03 '13 12:10

mzmm56


2 Answers

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

like image 172
c.P.u1 Avatar answered Nov 15 '22 14:11

c.P.u1


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.

  • http://www.west-wind.com/weblog/posts/2009/Mar/22/Internet-Explorer-Global-Variable-Blow-ups
  • http://blogs.msdn.com/b/alvar/archive/2009/10/22/internet-explorer-creates-global-variables-for-each-object-in-the-dom.aspx
  • http://www.shanison.com/2010/06/17/ie-id-and-javascript-global-variable/
  • http://www.2ality.com/2012/08/ids-are-global.html
like image 25
pete Avatar answered Nov 15 '22 15:11

pete