0

Sorry if this question is duplicate.

Recently I found jQuery would add global JavaScript variable after calling functions passing with DOM id, such as $('<div id="foo" />').appendTo() / $.html('<p id="bar" />). The variable is pointed to the DOM object with the same id, shown as these lines:

<body>
    <div id="container"></div>
    <!-- include jquery.js -->
    <script>
         typeof(foo);                                          // "undefined"
         typeof(bar);                                          // "undefined"

         $('<div id="foo"></div').appendTo('#container');
         $('#foo').html('<div id="bar"></div>');

         typeof(foo);                                          // "object"
         typeof(bar);                                          // "object"

         foo instanceof HTMLDivElement;                        // true
         bar instanceof HTMLDivElement;                        // true

         foo === $('#foo')[0];                                 // true
    </script>
</body>

Is this feature introduced in the API documentation? What happens exactly?

Regards!

IronBlood
  • 165
  • 5

1 Answers1

0

Thanks to @RoryMcCrossan, it is not related to jQuery.

<script>
    var x = document.createElement("div");
    x.setAttribute('id', 'bar');
    document.body.appendChild(x);
    window.bar instanceof HTMLDivElement;  // true
</script>

See more details to this question Do DOM tree elements with ids become global variables?

Community
  • 1
  • 1
IronBlood
  • 165
  • 5