I was today years old when I learned that every HTML element added to the DOM and given an id
is automatically added to the window
object using the name provided in the id
.
For example, <input type="text" id="txtName">
automatically creates the variable window.txtName
which points to this HTML element, in most/all(?) browsers. (I don’t even know how to check browser support for this feature!)
ChatGPT insists it is bad practice to reference HTML elements using these variables. However, it also states that this functionality is supported in all modern browsers and is not deprecated.
This being the case, why not use this feature? It makes code much clearer and more concise. Consider:
document.getElementById("txtName").value = "Hello"
vs
txtName.value = "Hello"
Obviously there could be naming conflicts with other variables, but if these variables are created automatically and there’s nothing we can do about it, simply using good naming practices and proper scoping should avoid conflicts.
Please help me understand why this is a bad practice/what I am missing, because as of now, I think it looks very appealing.
Also, what is the “official” name of this feature?