0

I had a javascript variable "foo" and a span tag id named "foo" as well. For some reason jQuery seemed like it was confusing the variable for the id if the variable hasn't been declared. So if I wrote the following:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>jQuery Test</title>
  <meta name="author" content="Test">

  <script src="js/jquery.min.js"></script>
  <!--<script>
      var foo = 100;
  </script>-->
</head>
<body>
    <span id="foo">200</span>
    <br>
    <hr>
    <br>
    <p id="test">Foo Value</p>

    <script>
        $("#test").html(foo);
    </script>
</body>
</html>

The html content of #foo gets selected. Is this a feature of jQuery or a bug or just another reason to follow the "DRY" rule?

Brian
  • 431
  • 8
  • 18
  • Please read up on scopes: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript. And, you are mixing up jQuery with (vanilla) Javascript - this is solely within the scope of Javascript :) As a hint: I've used to prefix my variables w/ `$` to avoid any overriding of global identifiers (which are within the `window` scope), like `$foo = $('#foo')` –  Aug 16 '16 at 12:12
  • 3
    This isn't a jQuery behaviour but a JS one. By default references to elements with `id` attributes get created as properties of the `window` object - the same as a global variable. – Rory McCrossan Aug 16 '16 at 12:14
  • 1
    This also has nothing to do with DRY. – JJJ Aug 16 '16 at 12:18

0 Answers0