Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is getElementById optional in some browsers? [duplicate]

When accessing elements by window.someThing, the "someThing" should be the name of html element. But what I see now, is that I can access an element by id in the same way, without document.getElementById. When has this been changed? It looks like it works in Chrome, IE, Firefox 13, but not in Firefox 12.

For example:

<div id="MyDiv">Content</div>

<script>
    MyDiv.innerHTML = "New Content";
</script>

Why does the example above work? Why don't I have to do:

var MyDiv = document.getElementById('MyDiv');

Is it something new, or has it always been possible and I just didn't know it?

like image 431
Alex Dn Avatar asked Nov 21 '12 12:11

Alex Dn


1 Answers

http://www.quirksmode.org/dom/w3c_core.html#gettingelements
It's been (mostly) implemented since IE 5.5

I can't really find any info on using the ID as variable name. I'd suggest on sticking to getElementById("MyDiv").doSomething instead of MyDiv.doSomething, to improve compatibility. Especially when you're writing larger scripts, you may mix up variable names with id's used in the page. getElementById ensures you "get" the DOM element.

like image 86
Cerbrus Avatar answered Oct 30 '22 12:10

Cerbrus