-1

I accidentally tried the below code

How does sample in the below script gets logged without selecting the element using a selector or assigning it to a variable

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    console.log(sample);
});
</script>
</head>
<body>

<p id="sample">If you click on me, I will disappear.</p>
<p class="sample">If you click on me, I will disappear.</p>
</body>
</html>
Rahul Yadav
  • 2,627
  • 5
  • 30
  • 52

1 Answers1

2

Element IDs are often automatically assigned to the global context in browsers, but it's not something to rely on.

https://html.spec.whatwg.org/multipage/nav-history-apis.html#named-access-on-the-window-object

window[name]

Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

console.log(window.xx);
<div id="xx"></div>

https://dev.to/buntine/dom-elements-with-ids-are-global-variables

user3840170
  • 26,597
  • 4
  • 30
  • 62
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320