Why use document.getElementById when I can directly refer to the DOM id in JavaScript?

dom, getelementbyid, javascript

Solution

Accessing a DOM element directly will give you a error if the element does not exist. Wheras if you use `getElementById` it will return `NULL`.

You also can't access all elements directly if they, for example, have dashes in their name (`some-id`), because JS variables can't contain dashes. You could however access tthem with `window['some-id']`.

Problem

Possible Duplicate: IE/Chrome: are DOM tree elements global variables here? I recently discovered that I can use in javascript any object from DOM with a direct reference to its id: ``` <div id="layer">IM A LAYER</div> <script> alert(layer.innerHTML); </script> ``` If this is true, what advantage I'd get using the getElementById method?

Original source

Related problems