简体   繁体   中英

Accessing an HTML-element by it's id DIRECTLY - What happens here?

I've discovered this behavior by accident:

I can access an HTML-element in JavaScript just by it's HTML attribute "id". Normally I used getElementById for that.

I have even write-access to it's properties.

Made this demo and tried it out in Firefox, Safari and Chrome. It worked everywhere.

 alert(test1.innerHTML); test1.innerHTML = 'Foobar'; alert(test1.innerHTML); 
 <div id="test1">Demo 123</div> 

So, to be honest: I'm astonished and confused because I haven't known that that's possible.

Moreover I ask myself: What sense does getElementById make when I can get and set the element directly? Sure: I'm aware that the inventors haven't incorporated the method without some intention.

Can anyone give me some explanations why I have access to elements via id-attribute?

And why one uses getElementById nevertheless?

As far as I remember, this behaviour was introduced by Internet Explorer. After a while, other vendors picked it up. I don't think it was ever standardized and, as such, might stop functioning at any time. Also, if you have a variable test1 in your code it will override the test1 defined by the controls.

Worth mentioning, in certain IE versions, trying to create a global variable with the same name as the id of an element fails . The book "JavaScript: The Definitive Guide" by David Flanagan also says that if the variable already exists in the global scope when the element is created, then the variable will not be overwritten by the element with the same id.

More on the subject here: Is there a spec that the id of elements should be made global variable? and here: Do DOM tree elements with ids become global variables?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM