javascript - Why does document.getElementById() function exist? -
this question has answer here:
when creating web pages have used function
var somevariable = document.getelementbyid('myid');
to reference element object. suggested me not necessary, because there such variable. it's name equal id. i've tested , seems work.
<div id="myid">some text</div> <a href="someplace" onclick="alert(myid.innerhtml)">click here</a>
this code works , alerts "some text" expected. there warning in firefox error console:
element referenced id/name in global scope. use wc3 standard document.getelementbyid() instead....
i using jquery need prove point boss @ work or else have have buy him box of chocolate :-).
any ideas why upper code shouldnt work or why wrong idea use it(warning in firefox not enough)???
thanks answers
any ideas why upper code shouldnt work or why wrong idea use it(warning in firefox not enough)???
because it's non-standard (but not long). although some browsers assign elements id global variables, there's no obligation them (and not of them do). older versions of firefox, instance, not exhibit behavior. there's risk of naming collisions.
using document.getelementbyid()
ensures browsers behave same (well, more or less cough) when getting handle element.
see bobince's excellent answer similar question more information.
Comments
Post a Comment