Why use document.getElementById when I can directly reference the DOM identifier in JavaScript?

Possible Duplicate:
IE / Chrome: Do DOM Tree Tree Elements Exist Here?

I recently discovered that I can use in javascript any object from the DOM with a direct link to its id:

<div id="layer">IM A LAYER</div>
<script>
   alert(layer.innerHTML);
</script>

If this is true, what advantage do I get with the getElementById method?

+5
source share
3 answers

Accessing the DOM element directly will result in an error if the element does not exist. If you use getElementById, it will return NULL.

, , , (some-id), JS . tthem window['some-id'].

+7

, script

<script>
var layer = false; // or any other assignment
</script>

layer window.layer, layer.innerHTML . document.getElementById .

+2

This will only work for those idcontaining letters allowed for variable names. For id, for example text-11or item-key-21, this will not work.

+1
source

All Articles