javascript - The business case for getElementById() -
it's understanding every modern browser, both desktop , mobile, surfaces elements ids global javascript namespace. still, people on industry keep using document.getelementbyid()
or jquery cousin $("#theid")
.
for cases not pathological (e. g. id matches object in global namespace), there reason doing so, other misplaced concern backwards compatibility? how far in time have go starts mattering?
edit: consider following:
<html> <body> <input type="hidden" id="foo" value="hello world"/> <input type="button" onclick="alert(foo.value);" value="press this"/> </body> </html>
it displays "hello world" on msie on windows, chrome, firefox, opera, safari on mac, safari on ipad, android browser, msie on windows phone... why use document.getelementbyid("foo").value
instead?
for cases not pathological (e. g. id matches object in global namespace)…
because literally any variable added global namespace, there no case "not pathalogical".
is there reason doing so, other misplaced concern backwards compatibility?
by convention avoid introducing global variables otherwise conflict existing global variables (e.x. don't declare var document
or var settimeout
). in fact, it's recommended avoid introducing any global variables @ enclosing them in scope somewhere.
if otherwise run maintenance issues. maintenance issues don't scale.
consider case have element [id="question"]
. if rely on global reference of question
refer element, , else working on project decides introduce question.js
module elsewhere, you're going have really hard time debugging issue.
the intent behind referencing question
dom node unclear, , means of accessing element equally unclear.
furthermore, how handle case id changes? if use document.getelementbyid(...)
need store reference dom node. if id changes, you'll have update selector in 1 place.
if start making use of global reference dom node, you'll need update all usages.
the reasons avoiding global references dom nodes has nothing compatibility, , fact it's terrible feature.
Comments
Post a Comment