+ 5

id in html and variables in JavaScript

i realized that when we add an id to html element. that element is accessible in JavaScript via its id like a usually variable . see code: https://code.sololearn.com/Wi60wsW3C1Q8/?ref=app if this work in all browsers, why we use document.getElementById

29th Apr 2021, 8:36 PM
Mehran
Mehran - avatar
7 Antworten
+ 6
[Part 1 of 2] Mirielle It would, indeed, seem like it should be a bug. 😉 Surprisingly... it is not. 😱 IIRC... this was originally an undocumented behavior in early versions of IE and eventually got adopted by other browser engines. Essentially, here's what's happening: Consider the example: <div id="msg">foo</div> ... is an HTML element with a non-empty id attribute containing the string value "msg". Such id values are added to the windows object as named indexed properties that can be accessed as: windows["msg"] As with any other Javascript object, if the indexed name (i.e. "msg") satisfies the rules for valid variable names, the value "msg" is also available as a getter property on the windows object as such: windows.msg Since the windows object is also the root globals container, the following would also suffice: msg Hence... this unfortunate scenario exists where HTML elements can be accessible as global variables. (continued...)
1st May 2021, 4:15 AM
David Carroll
David Carroll - avatar
+ 6
[Part 2 of 2] However, as any experienced developer knows, global variables should be avoided as a general rule and practice. Yet, for some reason, the _powers-that-be_ at WHATWG, in their not-so-infinite wisdom, eventually decided to make this part of the official HTML Living Standard. 🤷‍♂️ https://html.spec.whatwg.org/multipage/window-object.html#dom-window-nameditem-filter But... at the same time, they added a non-normative notice to discourage the use of these global nameditems in the windows object. 🤦‍♂️ https://html.spec.whatwg.org/multipage/window-object.html#named-access-on-the-window-object What a mess. 😣 Anyway... I hope this helps clarify what's going on. 👌
1st May 2021, 4:17 AM
David Carroll
David Carroll - avatar
+ 5
You should not use way of accessing DOM elements because it may work incorrectly on some browsers or if you use some JavaScript keywords as element ID. https://code.sololearn.com/WKM40WTo54u7/?ref=app
30th Apr 2021, 5:19 AM
Artem 🇺🇦
Artem 🇺🇦 - avatar
+ 4
Mehran than why did you mark your own answer as best and not David Carroll 's one?
1st May 2021, 5:47 AM
Artem 🇺🇦
Artem 🇺🇦 - avatar
+ 3
Mehran Ultimately, you don't want to rely on the implicitly created global variables as it could lead to some brittle code at best.
1st May 2021, 4:20 AM
David Carroll
David Carroll - avatar
+ 1
aku ingin belajar
1st May 2021, 5:03 PM
Brayen
Brayen - avatar