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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With