0

I'm new to JavaScript. What I have learnt so far is that we can access html element either through getElementById or querySelector. But I saw a code in which the html element has accessed directly through id but without using getElementById or querySelector .I have tested it. It is working .But I'm unable to understand how it is working. can anyone explain what is going on .It would be a great favor.

<html>
<head>
    <title></title>
    <script>
            document.addEventListener('DOMContentLoaded', function() {
            btn.addEventListener('click',()=>{
            test.innerHTML="Some value"
            alert(txt.value)
            })
        });
     
    </script>
</head>
<body>
    <input type="text" value="Ahtisham" id="txt">
    <p id="test">abc</p>
    <button id="btn" >Click me</button>
</body>
ahtisham ali
  • 1
  • 1
  • 3
  • This is ancient legacy behaviour of the browser whereby any ID given to an HTML element automatically creates a global variable whose name corresponds to that ID, which holds the element concerned. (I will try to find a link, either on SO or elsewhere.) It's horrible behaviour that you should never rely on. – Robin Zigmond Apr 21 '21 at 19:21
  • Yes, this is a standard feature, HTML elements having an unique id are exposed as global variables named with the id. But like Robin just said above, don't use it. – Teemu Apr 21 '21 at 19:21

0 Answers0