... 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.
--
Ed.
> 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.
>
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
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.
>>
--
Ed.
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
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.
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
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...
--
Jorge.
> 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
--
http://www.gregorkofler.com
http://web.gregorkofler.com - vxJS, a JS lib in progress
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
You mean 'a property with the name "foo"', of course.
PointedEars
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.
--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF3 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Indeed. That sounds more consistent.
<script type="text/javascript">
since almost a decade now. <http://validator.w3.org/>
>> redBook.style.visibility = "hidden";
>> redBook.style.cursor = "pointer";
IMHO no host-defined properties should be assumed to exist; all should be
feature-tested.
>> </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.
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
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.
[...]
--
Rob
[snip]
> Many thanks in advance.
Many thanks to everyone for the discussion.
(Replying to all own post but directed to everyone who contributed.)
--
Ed.
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.
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.
--
Jorge.
Idiotic pedantry, quite inappropriate in respect of an article
using partial code to illustrate particular points.
>Dr J R Stockton wrote:
>> Ed Weatherup posted:
>>> Why should I use ...
>>> [...]
>>> ... instead of ...
>>>
>>> <script>
>
> <script type="text/javascript">
>
>since almost a decade now. <http://validator.w3.org/>
>
>>> 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.
>>> </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.
>
>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.
--
(c) John Stockton, nr London UK. ???@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Reliability is preferable to asthetics.
>>>> </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.
>> 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.
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
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
[...]
>>> 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.
>
> 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
--
comp.lang.javascript FAQ: http://jibbering.com/faq/
> 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.
I tend to agree, but is it really better?
In IE, getElementById("redBook") returns the form
element, and so do older (bug compatible) versions of
Opera. Recent versions of Opera, and Firefox[1] return
the other element.
Better keep names and ids unique.
/Nisse
[1]: The one version I have installed.