Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String identitical to id of an element returns the element [duplicate]

I've encountered a situation which works but I dont understand why. If I name an element id="abc" and do console.log(abc) without setting it first, it gives me the HTML Object. Could anyone explain this behaviour?

Example

<h1 Id="abc" >abcdefghj</h1> 

<script>
  // without using document.getElementById
  console.log(abc); // Returns h1 element  
 </script>

I don't know why it's give me the whole element without using document.getElementById().

like image 481
Abhishek Kumar Avatar asked Feb 10 '20 08:02

Abhishek Kumar


1 Answers

This is a legacy feature of the DOM API: basically, anything with an ID is accessible by its key in the window object, i.e. window[id].

In your case, abc is essentially window.abc, which is a reference to the element with the ID of abc (i.e. matching the #abc selector).

This is also a reason why IDs in a HTML document must be unique, and that browser behavior of handling duplicated ID is technically undefined by spec.


On a related note, because of this feature, it is dangerous to give your elements IDs that may override native functions/prototypes. Here is an example: <button id="submit"> when located in a form. When you try to programmatically submit the form using formElement.submit(), you actually run into an error, because now the formElement.submit actually refers to the nested button element with the ID of submit instead of the native method. You can try this out yourself here:

const myForm = document.getElementById('myForm');

const helloButton = document.getElementById('btn');
helloButton.addEventListener('click', () => {
  myForm.submit();
})
<form id="myForm">
  <input type="text" />
  <button id="submit">
    Submit form
  </button>
  <button id="btn" type="button">
    Click me to programmatically submit form
  </button>
</form>
like image 193
Terry Avatar answered Nov 09 '22 21:11

Terry