Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directly reference HTML elements [duplicate]

Possible Duplicate:
IE/Chrome: are DOM tree elements global variables here?
why window[id] === document.getElementById( id )

I've just come across something in html/javascript which has surprised me a bit. When obtaining a reference to an html element, using javascript, I have always previously used either jQuery or document.getElementById. It also appears that you can directly access a element simply by using it's id. Can someone explain the nuances of this? I've googled but cannot find any reference to this ability, every site talks about getElementById.

The following page snippet illustrates this.

<html>
<head>
</head> 
<body>
    <input type="button" value="getElement" onclick="document.getElementById('blah').innerText = 'getElementById'" />
    <input type="button" value="direct" onclick="blah.innerText = 'direct';" />
    <div id="blah"></div>
</body>

Many thanks in advance.

like image 586
Sam Shiles Avatar asked Sep 10 '25 21:09

Sam Shiles


2 Answers

Being able to select elements on the page based on their [id] is a "feature" from early JavaScript (DOM lvl 0 or 1 methinks, can't seem to find the source).

Unfortunately it's a temperamental feature. What would happen if you had:

<div id="window"></div>

or

<div id="document"></div>

Better yet, what happens here?

<div id="foo"></div>
<div id="bar"></div>
<script>var foo = document.getElementById('bar');</script>

So the nuances to calling an element based on it's [id] is simply this:

Don't use it.

It's not consistent, and not guaranteed to receive future support.

Personally I'd like to see this "feature" go the way of document.all. It only causes more issues than it solves, and document.getElementById, while certainly verbose, is meaningful and understandable.

like image 95
zzzzBov Avatar answered Sep 12 '25 11:09

zzzzBov


Using getElementById is more flexible and readable. For instance, this won't work:

<input type="button" value="direct" onclick="document.innerText = 'direct';" />
<div id="document"></div>

for obvious reasons, but this will:

<input type="button" value="getElement" onclick="document.getElementById('document').innerText = 'getElementById'" />
<div id="document"></div>

and it's more clear to other developers what's really going on.

like image 45
Blazemonger Avatar answered Sep 12 '25 10:09

Blazemonger