Newbie question: Why getElementById?

E

Ed Weatherup

Apologies if this is answered elsewhere (although I have googled the
group and read the FAQ) but ...

.... why should I use document.getElementById instead of referring to the
HTML element directly?

Given the HTML fragment ...

<div id="redBook"> ... content ... </div>


Why should I use ...

<script>
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";
</script>


.... instead of ...

<script>
redBook.style.visibility = "hidden";
redBook.style.cursor = "pointer";
</script>

The reason I ask is that a colleague points to the warnings[1] in the
Firefox error console but other than saying "It's a W3C compliance issue
...." he is unable to explain further.


[1] Element referenced by ID/NAME in the global scope. Use W3c standard
document.getElementById() instead.

Many thanks in advance.
 
E

Evertjan.

Ed Weatherup wrote on 01 jul 2009 in comp.lang.javascript:
Apologies if this is answered elsewhere (although I have googled the
group and read the FAQ) but ...

... why should I use document.getElementById instead of referring to
the
HTML element directly?

Given the HTML fragment ...

<div id="redBook"> ... content ... </div>


Why should I use ...

<script>
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";
</script>


... instead of ...

<script>
redBook.style.visibility = "hidden";
redBook.style.cursor = "pointer";
</script>

These last two work only in IE and bad at that.

The reason I ask is that a colleague points to the warnings[1] in the
Firefox error console but other than saying "It's a W3C compliance
issue ..." he is unable to explain further.


[1] Element referenced by ID/NAME in the global scope. Use W3c
standard document.getElementById() instead.

Many thanks in advance.
 
E

Ed Weatherup

Evertjan. said:
Ed Weatherup wrote on 01 jul 2009 in comp.lang.javascript:


These last two work only in IE and bad at that.

That was my first thought but experiment shows that it works in Firefox,
Opera, Chrome and Safari.
The reason I ask is that a colleague points to the warnings[1] in the
Firefox error console but other than saying "It's a W3C compliance
issue ..." he is unable to explain further.


[1] Element referenced by ID/NAME in the global scope. Use W3c
standard document.getElementById() instead.

Many thanks in advance.
 
E

Erwin Moller

Ed Weatherup schreef:
Apologies if this is answered elsewhere (although I have googled the
group and read the FAQ) but ...

... why should I use document.getElementById instead of referring to the
HTML element directly?

Given the HTML fragment ...

<div id="redBook"> ... content ... </div>


Why should I use ...

<script>
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";
</script>


... instead of ...

<script>
redBook.style.visibility = "hidden";
redBook.style.cursor = "pointer";
</script>

The above is not correct.
It only 'works' in IE as far as I know.
IE likes to help the JavaScript programmer by solving bad JavaScript.

And you don't need to repeat the getElementById like you did:
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";

Try:
var myRedbook = document.getElementById("redBook");
myRedbook .style.visibility = "hidden";
myRedbook .style.cursor = "pointer";

You can also pass the reference (myRedbook) around to other functions
methods, like you can with every reference, eg:
makeMeBeautiful(myRedbook);

The reason I ask is that a colleague points to the warnings[1] in the
Firefox error console but other than saying "It's a W3C compliance issue
..." he is unable to explain further.

Well, what about the situation where there is a formelement or a form,
or whatever with the name "redBook" and also an id="redBook" elsewhere?
I don't know how IE solves that (nor care).
It is simply better to be clear AND stick to the standards, and thus use
getElementById.

Regards,
Erwin Moller

[1] Element referenced by ID/NAME in the global scope. Use W3c standard
document.getElementById() instead.

Many thanks in advance.


--
"There are two ways of constructing a software design: One way is to
make it so simple that there are obviously no deficiencies, and the
other way is to make it so complicated that there are no obvious
deficiencies. The first method is far more difficult."
-- C.A.R. Hoare
 
R

Richard Cornford

Ed Weatherup wrote:



These last two work only in IE and bad at that.
<snip>

Not any more (the only work in IE bit). A world of dodgy, IE only,
browser scripting on the web has forced many compromises from the
makers of other browsers and this is one. If it did not work in
Firefox there would be an error reported from Firefox's javascript
console instead of a warning.

On the other hand, it did (and probably still does) only work on
Firefox when it is rendering in Quirks mode (or not in 'Standards'
mode), is a relatively recent change and so will not work with the
older gecko-based browsers and is not guaranteed to work in any modern
W3C standard web browsers (so probably does not in at least some).

Richard.
 
P

Paul E. Schoen

"Erwin Moller"
Ed Weatherup schreef:

The above is not correct.
It only 'works' in IE as far as I know.
IE likes to help the JavaScript programmer by solving bad JavaScript.

And you don't need to repeat the getElementById like you did:
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";

Try:
var myRedbook = document.getElementById("redBook");
myRedbook .style.visibility = "hidden";
myRedbook .style.cursor = "pointer";

You can also pass the reference (myRedbook) around to other functions
methods, like you can with every reference, eg:
makeMeBeautiful(myRedbook);

This is probably one of the anomalies of a language that is not strictly
typed (such as Delphi Pascal and to a lesser extent C), but rather plays
fast and loose with automatic conversions of variables that are strings,
pointers, numbers, and object identifiers. This seems even more the case in
Perl. Perhaps it is also a characteristic of a language that is designed to
be interpreted rather than compiled. But I would rather make an explicit
typecast if a variable is to be interpreted as something other than what I
originally intended, or make it a variant.

I am used to looking at things at the low level where a string such as
"redBook" is actually an array of characters in memory. redBook.style would
be a pointer to a structure or object in memory that has a property called
style. But first the object would need to be created, or at least the name
would have to be assigned as the pointer to the existing object.

It is a little disturbing that the browser would automagically make that
assignment. But in actuality I think the HTML that creates a document
element with an id="string" creates it as an object with an identifier that
has the name of the string. So the shortcut method of simply using
string.property seems just as valid as having to use
document.getElementById("redBook").

Just my attempt at understanding...

Paul
 
J

Jorge

Paul said:
(...)
But in actuality I think the HTML that creates a document
element with an id="string" creates it as an object with an identifier that
has the name of the string. So the shortcut method of simply using
string.property seems just as valid as having to use
document.getElementById("redBook").

It's ok to query the DOM for an object whose "name" is this of whose
"id" is that, but it's not ok to expect that name to be defined as a
global in the JavaScript environment (which is another, different
context). What would happen if instead of redBook you had chosen to name
it window or Math or document ?

HTMLElements belong to the DOM, let's not make a gazpacho...
 
G

Gregor Kofler

Paul E. Schoen meinte:
It is a little disturbing that the browser would automagically make that
assignment. But in actuality I think the HTML that creates a document
element with an id="string" creates it as an object with an identifier that
has the name of the string. So the shortcut method of simply using
string.property seems just as valid as having to use
document.getElementById("redBook").

foo.style tries to access a style property of an object named foo in the
local scope. If foo is not present in the local scope the parent scopes
are searched until it ends in the global scope. All that IE does is to
create globally available variables holding references to the according
elements with their id property, which determines the name of the variable.

*Only* the latter method is valid. The first one works occasionally by
coincidence in a couple of browsers.

Gregor
 
P

Paul E. Schoen

Jorge said:
It's ok to query the DOM for an object whose "name" is this of whose "id"
is that, but it's not ok to expect that name to be defined as a global in
the JavaScript environment (which is another, different context). What
would happen if instead of redBook you had chosen to name it window or
Math or document ?

HTMLElements belong to the DOM, let's not make a gazpacho...

Good point. But good practice IMHO would be not to use any reserved word as
an identifier. However, things are as they are, and if getElementById is
preferred, then I don't see any problem.

But in the context of JavaScript in PDF, at least Nitro Pro, there is no
such function, and even "document" does not seem to be a valid object. When
writing JavaScript for a text field, I had to use
this.getField("FieldName") or this.fieldName("FieldName"). Also when using
JavaScript in the context of the WSH, there is no document or HTML ids.
Those are the contexts I am most concerned with at the moment.

Paul
 
T

Thomas 'PointedEars' Lahn

Gregor said:
Paul E. Schoen meinte:

foo.style tries to access a style property of an object named foo in the ^^^^^^^^^^^^^^^^^^^
local scope.

You mean 'a property with the name "foo"', of course.


PointedEars
 
D

Dr J R Stockton

In comp.lang.javascript message said:
Why should I use ...

<script>
document.getElementById("redBook").style.visibility = "hidden";
document.getElementById("redBook").style.cursor = "pointer";
</script>


... instead of ...

<script>
redBook.style.visibility = "hidden";
redBook.style.cursor = "pointer";
</script>

You should use the latter; but redBook must be a reference to the
element; that of course requires the element already to exist.

You can make it a reference by using
redBook = document.getElementById("redBook")
but there must be no other ID redBook.

And document.getElementById("redBook") should not be repeated
unnecessarily, since that is bulky and inefficient.

You should decide whether you will use only constructs specified in the
applicable international standards, or whether working in all tested
browsers is good enough. Remember, though, that the Web can be used
through many agents - not just PC browsers - and that standards-
compliance is at best a majority pursuit.

You may be able to get a reliable reference in ways other than global
search; for example, if you have a <form> containing <input type=button
onClick="XXX(this)">, then within function XXX(B) { ... } you have B
as a reference to the button and B.form as a reference to the form and
B.form.Y as a reference to an item named Y in the form. Such local
references are more elegant and should be more efficient.

It's a good idea to read the newsgroup c.l.j and its FAQ. See below.
 
T

Thomas 'PointedEars' Lahn

Dr said:
Ed Weatherup posted:
Why should I use ...
[...]
... instead of ...

<script>

<script type="text/javascript">


IMHO no host-defined properties should be assumed to exist; all should be
feature-tested.
You should use the latter; but redBook must be a reference to the
element; that of course requires the element already to exist.

You can make it a reference by using
redBook = document.getElementById("redBook")
but there must be no other ID redBook.

It should be

var redBook = document.getElementById("redBook");

(or `redBook' declared before) because the assignment throws an
exception in MSHTML otherwise (thanks to the "syntactic sugar").


PointedEars
 
R

RobG

This is probably one of the anomalies of a language that is not strictly
typed

That is completely irrelevant. It is a consequence of an
implementation decision by Microsoft to make HTML element ID and NAME
attributes global variables by default. It "works" in other browsers
to some extent as a consequence of IE's market dominance forcing them
to implement similar features.

(such as Delphi Pascal and to a lesser extent C), but rather plays
fast and loose with automatic conversions of variables that are strings,
pointers, numbers, and object identifiers.

There are no pointers in ECMAScript, nor specifically "object
identifiers". There are identifiers that might be variables whose
value is a reference to an object.

This seems even more the case in
Perl. Perhaps it is also a characteristic of a language that is designed to
be interpreted rather than compiled. But I would rather make an explicit
typecast if a variable is to be interpreted as something other than what I
originally intended, or make it a variant.

Nothing to do with the issue, type casting would not make any
difference here. The discussion is about two different ways to get a
reference to the same object, a DOM HTML element.

[...]
 
E

Ed Weatherup

Ed said:
Apologies if this is answered elsewhere (although I have googled the
group and read the FAQ) but ...

[snip]

Many thanks in advance.

Many thanks to everyone for the discussion.

(Replying to all own post but directed to everyone who contributed.)
 
R

Richard Cornford

Jorge wrote in message

Good point. But good practice IMHO would be not to use any
reserved word as an identifier.
<snip>

In javascript the definition of being an Identifier includes not being
a reserved word. Of course javascript has a very strict idea of what
'Identifier' and 'Reserved Word' mean, and you may not be using either
in those senses.

Richard.
 
J

Jorge

Gregor said:
Thomas 'PointedEars' Lahn meinte:

Indeed. That sounds more consistent.

Sure of course: "access a style property of a property with the name
foo" sounds much better, yes yes indeed -as we all know- it's a property
of properties to have properties.
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>, Thu,
2 Jul 2009 01:04:05, Thomas 'PointedEars' Lahn <[email protected]>
posted:

Idiotic pedantry, quite inappropriate in respect of an article
using partial code to illustrate particular points.
Dr said:
Ed Weatherup posted:
Why should I use ...
[...]
... instead of ...

<script>

<script type="text/javascript">


IMHO no host-defined properties should be assumed to exist; all should be
feature-tested.

This is partial code. The properties may already have been shown to
exist, and it is not reasonable to test existence every time they are
referred to. Plus, of course, it would add noise to the illustration.
It should be

var redBook = document.getElementById("redBook");

(or `redBook' declared before) because the assignment throws an
exception in MSHTML otherwise (thanks to the "syntactic sugar").

It should not be; again, what I wrote is something that should be used,
not a draft statement. It is also something written in the knowledge
that the prime reader should be able to read English in the manner
expected of a native speaker of the Queen's English.

When you have nothing useful to add, it is better to add nothing.
 
T

Thomas 'PointedEars' Lahn

Dr said:
Thomas 'PointedEars' Lahn posted:
Dr said:
Ed Weatherup posted:
Why should I use ... [...] ... instead of ...

<script>
<script type="text/javascript">

since almost a decade now. said:
redBook.style.visibility = "hidden"; redBook.style.cursor =
"pointer";
IMHO no host-defined properties should be assumed to exist; all should
be feature-tested.

This is partial code. The properties may already have been shown to
exist, and it is not reasonable to test existence every time they are
referred to. Plus, of course, it would add noise to the illustration.

Reliability is preferable to asthetics.
It should not be; again, what I wrote is something that should be used,
not a draft statement.

And therefore the declaration is necessary.
It is also something written in the knowledge that the prime reader
should be able to read English in the manner expected of a native speaker
of the Queen's English.

Obnoxiously right-winged, but typical for you.
When you have nothing useful to add, it is better to add nothing.

Why don't you follow your own advice for a change?


PointedEars
 
G

Garrett Smith

Thomas said:
Dr said:
Thomas 'PointedEars' Lahn posted:
[...]
It should not be; again, what I wrote is something that should be used,
not a draft statement.

And therefore the declaration is necessary.

You're trying to point out that omitting "var" results in error in IE.
"Object doesn't support this property or method".

Was explained here,
http://jibbering.com/faq/names/extra_props_global.html
and in Lasse's post, linked therein.

Garrett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,002
Messages
2,570,258
Members
46,858
Latest member
FlorrieTuf

Latest Threads

Top