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().
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With