Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 879
Alkarod Avatar asked Jan 23 '13 11:01

Alkarod


People also ask

Why do we use document getElementById in JavaScript?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

Do I need getElementById?

Using getElementById is the only good way to access the element, which can be done either by itself or preferably, with a function so that we can more appropriately handle errors if it can't be found. For allowing access to elements blocked by global id, this one goes to getElementById.

Does getElementById only work on document?

An element with an ID is unique no matter what its parent is. Therefore, it's uncessary to know the parent of an element before getting that element using its ID. So, there's no need to put the function getElementById on all elements, putting it only on document will suffice.

What does getElementById return if there is no such element with that ID?

Introduction to JavaScript getElementById() method If the document has no element with the specified id, the document. getElementById() returns null . Because the id of an element is unique within an HTML document, the document. getElementById() is a quick way to access an element.


2 Answers

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'].

like image 60
Jan Hančič Avatar answered Oct 16 '22 14:10

Jan Hančič


for example, if in your page you have elsewhere another previous script with

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

layer will be a reference to window.layer, then layer.innerHTML will fail. With document.getElementById you will avoid this tricky errors

like image 30
Fabrizio Calderan Avatar answered Oct 16 '22 15:10

Fabrizio Calderan