Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Changing text between <div>'s

1 view
Skip to first unread message

Ton den Hartog

unread,
Dec 26, 2003, 5:34:27 AM12/26/03
to
Stupid basic question but I find it horribly imposible to find the answer
elsewhere... :-(

I want to have a piece of text in my HTML page and want to be able to change
it in a Javascript function that is called from a button. I think I can use
a

<div id="t"></div>

for this ? Something like

document.t.value="Hello"

should change it into

<div id="t">Hello</div>

I am getting fucking mad at finding these simple things.... Is there a good
intro somewhere ? My thick Oreilly JS book is just too busy with the
complicated stuff somehow :-((

Ton

--
--
Computer museum tonh: http://www.tonh.net/museum - 10.000 visitors !!
GGGallery website generator: http://www.tonh.net/gggallery
Vrij Kunst Centrum : http://www.meesterschap.nu

Ton den Hartog

unread,
Dec 26, 2003, 6:18:59 AM12/26/03
to
Ok, already solved it. Remembered I asked this once before....

document.getElementById('t').firstChild.nodeValue="Hello";

Unbelievable how complex.... Will look for the model of this....

Thanks,

Ton

--
--
Computer museum tonh: http://www.tonh.net/museum - 10.000 visitors !!
GGGallery website generator: http://www.tonh.net/gggallery
Vrij Kunst Centrum : http://www.meesterschap.nu


"Ton den Hartog" <ton.den.hart...@tonh.net> wrote in message
news:3fec0eb5$0$321$e4fe...@news.xs4all.nl...

Ton den Hartog

unread,
Dec 26, 2003, 6:19:38 AM12/26/03
to
Why is this so complex ??? Why does DOM not have an easy model for this ????

Ton

--
--
Computer museum tonh: http://www.tonh.net/museum - 10.000 visitors !!
GGGallery website generator: http://www.tonh.net/gggallery
Vrij Kunst Centrum : http://www.meesterschap.nu


"Ton den Hartog" <ton.den.hart...@tonh.net> wrote in message

news:3fec1926$0$327$e4fe...@news.xs4all.nl...

Jim Ley

unread,
Dec 26, 2003, 6:27:12 AM12/26/03
to
On Fri, 26 Dec 2003 12:19:38 +0100, "Ton den Hartog"
<ton.den.hart...@tonh.net> wrote:

>Why is this so complex ??? Why does DOM not have an
>easy model for this ????

DOM is not designed to be simple it's designed to be consistent across
programming languages, I have no idea why that was a design aim, but
it is, this means what can be done simply in typeless scripting
language doesn't get into the language if it would make the java or
LISP binding more complicated.

It's often best to use the proprietary methods, as these generally are
optimised for scripting, and only fallback to DOM if they don't work.

Jim.
--
comp.lang.javascript FAQ - http://jibbering.com/faq/

Ton den Hartog

unread,
Dec 26, 2003, 6:51:49 AM12/26/03
to
> It's often best to use the proprietary methods

Which is in this case ?

Thanks,

Ton

Fabian

unread,
Dec 26, 2003, 8:19:37 AM12/26/03
to
Ton den Hartog hu kiteb:

>> It's often best to use the proprietary methods
>
> Which is in this case ?

document.t.innerhtml

You'll want to double check the case - its sensitive iirc.


--
--
Fabian
Visit my website often and for long periods!
http://www.lajzar.co.uk

Lasse Reichstein Nielsen

unread,
Dec 26, 2003, 8:58:49 AM12/26/03
to
"Fabian" <laj...@hotmail.com> writes:

> Ton den Hartog hu kiteb:
>
>>> It's often best to use the proprietary methods
>>
>> Which is in this case ?
>
> document.t.innerhtml

That would fail in all browsers :)

Even if you write it "innerHTML", it would still fail in IE and probably
also other browsers.

To get the element to change, use
document.getElementById("t")
That is the method that works in the most current browsers.
If you need to support IE 4 (or possibly WebTV), you can
use a fallback to the document.all collection:
---
var elem;
if (document.getElementById) {
elem = document.getElementById("t");
} else if (document.all) { // IE 4 and a few other
elem = document.all["t"];
} // else (e.g., Netscape 4) panic.
---
Just writing "document.t" assumes that the named element is made a
property, with the same name, of the document element. That is not
the case in, e.g., Internet Explorer. (Using just "t.innerHTML"
would break in Mozilla/Netscape for similar reasons - just use
getElementById!)

You can then change the content with the proprietary (but widely
implemented) innerHTML property:

var elem = document.getElementById("t");
elem.innerHTML = "some <em>HTML<\/em> content";

If you want to check for the existence of the innerHTML property
before using it, you have two choices:
Simple:

var elem = document.getElementById("t");
if (elem.innerHTML) { ... }

That has the disadvantage of creating a very large string if elem has
a lot of content already. That is inefficient.

Smart, but dangerous:
var elem = document.getElementById("t");
if ("innerHTML" in elem) { ... }

That has the disadvantage of not working in older browsers. I am not
sure any of those support "innerHTML", but that kind of ruins the
idea of testing.

The syntax ("name" in obj) was introduced in JScript 1.0 (according to
MSDN, so IE it should work in any version of IE), and JavaScript 1.4
(Netscape 6 and later, not Netscape 4). The very bad thing about it
is, that browsers that don't support it, treats it as a syntax error.
That means that it breaks the entire script block it is in.



> You'll want to double check the case - its sensitive iirc.

Yes, Javascript is case sensitive.

/L
--
Lasse Reichstein Nielsen - l...@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'

DU

unread,
Dec 26, 2003, 12:47:57 PM12/26/03
to
Jim Ley wrote:
> On Fri, 26 Dec 2003 12:19:38 +0100, "Ton den Hartog"
> <ton.den.hart...@tonh.net> wrote:
>
>
>>Why is this so complex ??? Why does DOM not have an
>>easy model for this ????
>
>
> DOM is not designed to be simple it's designed to be consistent across
> programming languages, I have no idea why that was a design aim, but
> it is, this means what can be done simply in typeless scripting
> language doesn't get into the language if it would make the java or
> LISP binding more complicated.
>
> It's often best to use the proprietary methods,

I disagree. CharacterData attributes and methods are widely and well
supported in recent browsers. If we are talking about text nodes only
(CharacterData objects), then use of proprietary methods is not
recommendable. If we are talking about element nodes, then this is a
different issue.

Unless someone can prove me wrong, all DOM2 CharacterData attributes and
methods are supported 100% by the following browsers:
Safari 1.x
Konqueror 3.x
MSIE 6 for Windows
Mozilla-based browsers (17 browsers) based on Mozilla 1.x
Opera 7.x

So why use anything else than CharacterData attributes and methods?

DU

DU

unread,
Dec 26, 2003, 12:59:32 PM12/26/03
to
Jim Ley wrote:


In my own tests, MSIE 6 for windows, Mozilla 1.x, NS 7.1 all render text
node changes 300% faster if you change the text node with W3C DOM
nodeValue than by resorting to innerHTML. This percentage is as high/big
as 2000% on some Opera 7.x versions.
The performance gain will be greater for long text nodes and slow cpu.
The performance gain will be smaller for short text nodes and fast cpu.

Performance comparison between innerHTML attribute and DOM's nodeValue
when modifying the text data of a node of type TEXT_NODE:
http://www10.brinkster.com/doctorunclear/HTMLJavascriptCSS/innerHTMLvsNodeValue.html

DOM level 2 CharacterData Interface tests
http://www10.brinkster.com/doctorunclear/HTMLJavascriptCSS/DOM2CharacterData.html

DU

DU

unread,
Dec 26, 2003, 1:17:50 PM12/26/03
to
Ton den Hartog wrote:

> Ok, already solved it. Remembered I asked this once before....
>
> document.getElementById('t').firstChild.nodeValue="Hello";
>
> Unbelievable how complex.... Will look for the model of this....
>
> Thanks,
>
> Ton
>

Your original code was itself part of the problem. When you write

<div id="t"></div>

then there is no firstChild node in such code. No childNodes either.
MSIE 6 for Windows, Mozilla 1.7alpha, Opera 7.50 PR1 all return null
when querying for document.getElementById("t").firstChild. Just by
inserting a single word or blank space in that div would have made a
difference though.

Further reading:
Nodes:
http://www.quirksmode.org/dom/intro.html#nodes

The Document Object Model (DOM):
The Simple Document's Diagram
http://webreference.com/js/column40/drawsimple.html
(Reading the entire article is best)

DU

Jim Ley

unread,
Dec 26, 2003, 5:03:50 PM12/26/03
to
On Fri, 26 Dec 2003 12:59:32 -0500, DU <drun...@hotWIPETHISmail.com>
wrote:

>Performance comparison between innerHTML attribute and DOM's nodeValue
>when modifying the text data of a node of type TEXT_NODE:
>http://www10.brinkster.com/doctorunclear/HTMLJavascriptCSS/innerHTMLvsNodeValue.html

You're assuming that speed matters.

You're also not doing any of the error trapping, to trap the
childNodes one you need to test for the existence of childNodes and of
childNodes[0], which you do not do this will further degrade
performance.

However in specific examples W3 DOM might be faster at the expense of
complexity and it's certainly worth using them with appropriate
checks, the problem is for the novice scripter understanding DOM and
ensuring it's safe isn't so easy, hence the OP's question.

DU

unread,
Dec 26, 2003, 6:23:37 PM12/26/03
to
Jim Ley wrote:
> On Fri, 26 Dec 2003 12:59:32 -0500, DU <drun...@hotWIPETHISmail.com>
> wrote:
>
>
>>Performance comparison between innerHTML attribute and DOM's nodeValue
>>when modifying the text data of a node of type TEXT_NODE:
>>http://www10.brinkster.com/doctorunclear/HTMLJavascriptCSS/innerHTMLvsNodeValue.html
>
>
> You're assuming that speed matters.
>

I'm just noticing that speed is a little bonus on top of
interoperability and compliance to standards.
If you know what you're doing, then you no longer need to resort to
innerHTML (and innerText, etc...) anymore: one code fits all recent
browsers. It's not just modifying nodeValue but all the other
CharacterData methods as well (inserting, replacing, deleting,
appending) which are now very well supported by recent browser versions.

> You're also not doing any of the error trapping, to trap the
> childNodes one you need to test for the existence of childNodes and of
> childNodes[0], which you do not do


Fair enough. I've updated the function with:
if(arrAllTheParg[PargIterator].childNodes[0] &&
arrAllTheParg[PargIterator].childNodes[0].nodeType == 3)
in the for loop.

this will further degrade
> performance.
>

Not much degradation. Maybe 50msec to 100msec on my PC. It's still
considerably faster to use DOM nodeValue instead of innerHTML.
I changed the "300%" to "200%".

> However in specific examples W3 DOM might be faster at the expense of
> complexity and it's certainly worth using them with appropriate
> checks, the problem is for the novice scripter understanding DOM and
> ensuring it's safe isn't so easy, hence the OP's question.
>
> Jim.

I would say that a majority of text changes in usual pages involve only
a few words, or a line, maybe a 2 line paragraph at the most (not 15KB
of text like in my testpage). In which case, using innerHTML or
firstChild.nodeValue or innerText (if applicable) won't make a lot of
difference in speed, performance.

DU

Thomas 'PointedEars' Lahn

unread,
Dec 26, 2003, 9:09:31 PM12/26/03
to
Jim Ley wrote:

> It's often best to use the proprietary methods, as these generally are
> optimised for scripting, and only fallback to DOM if they don't work.

This approach is utter nonsense as it makes scripts incompatible by
default, and we do not have to talk about their perspective to work
in the foreseeable future. Standards have been established to be
followed, not to be avoided. That is not a matter of whether you
like them or not, but a matter of getting dependent on the moods of
one particular vendor and his products, or not.


PointedEars

Jim Ley

unread,
Dec 26, 2003, 9:18:40 PM12/26/03
to
On Sat, 27 Dec 2003 03:09:31 +0100, Thomas 'PointedEars' Lahn
<Point...@web.de> wrote:

>Jim Ley wrote:
>
>> It's often best to use the proprietary methods, as these generally are
>> optimised for scripting, and only fallback to DOM if they don't work.
>
>This approach is utter nonsense as it makes scripts incompatible by
>default,

incompatible with what by default, it's ludicrous to talk about
incompatibility without talking about what it it incompatible with.

There's no single solution that reaches 100% every solution is
incompatible with some user agents.

>and we do not have to talk about their perspective to work
>in the foreseeable future.

Most pages are written for the foreseeable future, in any case,
there's no new browsers on the horizon in the HTML world, and those
that exist and are being worked on are all implementing the same old
proprietary scripts.

The future holds much more chances of X-Smiles or DENG becoming more
important, and no HTML pages are going to be relevant, let alone their
scripting.

> Standards have been established to be
>followed, not to be avoided.

We've already established that some proprietary is ok to be used
(document, setTimeout etc. being the most relevant) if some is okay,
then you have to make explicit what the objective criteria you're
using to choose which are allowed and which aren't.

Thomas 'PointedEars' Lahn

unread,
Dec 26, 2003, 11:58:25 PM12/26/03
to
Jim Ley wrote:

> On Sat, 27 Dec 2003 03:09:31 +0100, Thomas 'PointedEars' Lahn

>>Jim Ley wrote:
>>> It's often best to use the proprietary methods, as these generally are
>>> optimised for scripting, and only fallback to DOM if they don't work.
>>
>>This approach is utter nonsense as it makes scripts incompatible by
>>default,
>
> incompatible with what by default, it's ludicrous to talk about
> incompatibility without talking about what it it incompatible with.

Incompatibility with other user agents, previous and future versions
of the same UA, versions of the same UA running on other platforms,
and other document types and thus other DOMs supported by the same UA.

> There's no single solution that reaches 100% every solution is
> incompatible with some user agents.

True, nevertheless proprietary code is error-prone code
and should be avoided where possible, not been looked for.


PointedEars

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 12:36:12 AM12/27/03
to
Jim Ley wrote:

> On Sat, 27 Dec 2003 03:09:31 +0100, Thomas 'PointedEars' Lahn

>> Standards have been established to be followed, not to be avoided.
>
> We've already established that some proprietary is ok to be used
> (document, setTimeout etc. being the most relevant) if some is okay,
> then you have to make explicit what the objective criteria you're
> using to choose which are allowed and which aren't.

There is a difference between "not allowed" and "not (to be)
recommended". I argued for the latter, *knowing* that one
sometimes is required to use proprietary code *additionally*
to accomplish something because a standard for the feature is
(still) missing (take graphics filters in CSS for example.)

Besides, I do not accept `document' being called proprietary in
general. It can be (and is in Mozilla/5.0) a way of implementing
the W3C-DOM interface to be practical. `document instanceof
Document' yields `true' and Document.constructor yields `[object
DOM Constructor.prototype]' in Mozilla/5.0, so AFAIS the Document
object in *this* UA implements what is specified in the W3C-DOM.
If M$ did not implement the W3C-DOM in this way (and so far I am
missing a Document object in IE), it is their problem.


PointedEars

Lasse Reichstein Nielsen

unread,
Dec 27, 2003, 12:52:42 AM12/27/03
to
Thomas 'PointedEars' Lahn <Point...@web.de> writes:

> Besides, I do not accept `document' being called proprietary in
> general.

What do you mean by "in general"? And, just to be clear, what do you
mean by the word "proprietary"?

The existence of a global variable called "document" is not part
of any W3C recommendation or standards body published standard.
For my definition of "proprietary", that makes that global
variable (a.k.a. property of the global object) proprietary.
The value of the variable is irrelevant.

Jim Ley

unread,
Dec 27, 2003, 6:50:42 AM12/27/03
to
On Sat, 27 Dec 2003 05:58:25 +0100, Thomas 'PointedEars' Lahn
<Point...@web.de> wrote:

>Incompatibility with other user agents, previous and future versions
>of the same UA, versions of the same UA running on other platforms,
>and other document types and thus other DOMs supported by the same UA.

Firstly why is that a problem, you're using object detection, your
code won't error in these other systems, you're code degrades to
something usable if the method fails, all that is lost is that these
other browsers don't get your enhanced functionality.

It's probably worth choosing methods which give you the enhanced
functionality in many UA's, and many proprietrary methods can do this,
just like DOM ones.

There's an interesting argument in using proprietrary whereby you have
a lot smaller level of UA's to attempt authoring on, so if FredBrowser
6.5 has a broken DOM method which errors, it'll ignore your
proprietrary method, but use attempt the DOM one resulting in an
error. Proprietrary gives you a lot smaller test regime. Of course
FredBrowser and others which don't error won't get the enhanced
functionality, but that isn't a disaster.

>True, nevertheless proprietary code is error-prone code

Could you explain what's error prone about it?

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 10:13:57 AM12/27/03
to
Lasse Reichstein Nielsen wrote:

> Thomas 'PointedEars' Lahn <Point...@web.de> writes:
>> Besides, I do not accept `document' being called proprietary in
>> general.
>
> What do you mean by "in general"?

It does not apply for all UAs.

> And, just to be clear, what do you mean by the word "proprietary"?

A feature not based upon standards in any way.

> The existence of a global variable called "document" is not part
> of any W3C recommendation or standards body published standard.

1. `document' is an instance of the Document object in Mozilla/5.0.

2. The Document object is defined in the W3C-DOM Level 2 ECMAScript
language binding.

3. JavaScript 1.5, as supported by Mozilla/5.0, is fully compatible
with ECMAScript 3.

4. Mozilla/5.0's Document object defines a prototype that has the
same properties as the Document object of the W3C DOM 2.

5. `document' is a way of implementing the W3C-DOM in this UA.
It is not a proprietary feature.

6. `document' in the DOM of the IE browser component is not based
upon the W3C-DOM Document object. It is a proprietary feature
in *this* UA.


PointedEars

Lasse Reichstein Nielsen

unread,
Dec 27, 2003, 12:27:50 PM12/27/03
to
Thomas 'PointedEars' Lahn <Point...@web.de> writes:

> Lasse Reichstein Nielsen wrote:

>> What do you mean by "in general"?
>
> It does not apply for all UAs.

Ok.

>> And, just to be clear, what do you mean by the word "proprietary"?
>
> A feature not based upon standards in any way.

Agree.

>> The existence of a global variable called "document" is not part
>> of any W3C recommendation or standards body published standard.
>
> 1. `document' is an instance of the Document object in Mozilla/5.0.

No, 'document' is a string of eight characters.
When used in a Javascript program as a variable, it is (unless
declared by the user) a global variable, and as such refers to a
property of the global object.

*The existence of that variable* is not based on any standard.

The *variable* is prorietary. The object it refers to is not.

...


> 5. `document' is a way of implementing the W3C-DOM in this UA.
> It is not a proprietary feature.

If I make a browser with no global "document" variable, but a global
variable was called "arglebargle" that refers to an object
implementing of the W3C DOM's Document interface ... would that be
proprietary?

If yes, so is the variable "document".
If no, why not?

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 12:41:56 PM12/27/03
to
Lasse Reichstein Nielsen wrote:

> Thomas 'PointedEars' Lahn <Point...@web.de> writes:
>> Lasse Reichstein Nielsen wrote:
>>> The existence of a global variable called "document" is not part
>>> of any W3C recommendation or standards body published standard.
>>
>> 1. `document' is an instance of the Document object in Mozilla/5.0.
>
> No,

Do I need to remember you that `document instanceof Document'
yields `true' *there*? It is indeed an instance of the Document
object *there*.

> 'document' is a string of eight characters.

It is an *identifier* consisting of eight characters.


PointedEars

Lasse Reichstein Nielsen

unread,
Dec 27, 2003, 1:34:35 PM12/27/03
to
Thomas 'PointedEars' Lahn <Point...@web.de> writes:

> Lasse Reichstein Nielsen wrote:
>
>> Thomas 'PointedEars' Lahn <Point...@web.de> writes:

> Do I need to remember you that `document instanceof Document'

(remind)


> yields `true' *there*? It is indeed an instance of the Document
> object *there*.

Yes, the *value* that the variable refers to, is an instance of the
prototype of the function object referred to by the variable
"Document".

I was never talking about the value, just the variable itself.

>> 'document' is a string of eight characters.
>
> It is an *identifier* consisting of eight characters.

Yes. When that string is used in a Javascript program, it is an
identifier. That identifier can then be a variableExpression.
That variableExpression will, when evaluated, be looked up as
a property of the global object. Whether that succedes is not
specified in any standard.

Jim Ley

unread,
Dec 27, 2003, 3:45:58 PM12/27/03
to
On Sat, 27 Dec 2003 18:41:56 +0100, Thomas 'PointedEars' Lahn
<Point...@web.de> wrote:

>Lasse Reichstein Nielsen wrote:
>
>> Thomas 'PointedEars' Lahn <Point...@web.de> writes:
>>> Lasse Reichstein Nielsen wrote:
>>>> The existence of a global variable called "document" is not part
>>>> of any W3C recommendation or standards body published standard.

However it is in a current Working Draft. (not for an HTML UA though)

>>> 1. `document' is an instance of the Document object in Mozilla/5.0.
>>
>> No,
>
>Do I need to remember you that `document instanceof Document'
>yields `true' *there*? It is indeed an instance of the Document
>object *there*.

So,

fred=evt.srcElement.ownerDocument;

makes fred an instanceOf Document too, it doesn't make fred standard,
it's just a variable, like document is. (the code's obviously only
relevant in certain situations.)

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 4:27:58 PM12/27/03
to
Jim Ley wrote:

> fred=evt.srcElement.ownerDocument;
>
> makes fred an instanceOf Document too,

There is no Document object in the DOM of the IE browser
component. Can you name another UA where the above works
where there is a Document object?


PointedEars

Jim Ley

unread,
Dec 27, 2003, 4:32:34 PM12/27/03
to
On Sat, 27 Dec 2003 22:27:58 +0100, Thomas 'PointedEars' Lahn
<Point...@web.de> wrote:

>Jim Ley wrote:
>
>> fred=evt.srcElement.ownerDocument;
>>
>> makes fred an instanceOf Document too,
>
>There is no Document object in the DOM of the IE browser
>component.

Where did I mention IE?

> Can you name another UA where the above works
>where there is a Document object?

ASV, CSV, Batik...

Ton den Hartog

unread,
Dec 27, 2003, 8:41:35 PM12/27/03
to
> document.getElementById('t').firstChild.nodeValue="Hello";

That works. But what if I want a HTML element in the tag. When I use
"Hello<br>world" I get a LITERAL <br> in my browser-screen !! :-( How can I
prevent that ?

Ton

--
--
Computer museum tonh: http://www.tonh.net/museum - 10.000 visitors !!
GGGallery website generator: http://www.tonh.net/gggallery
Vrij Kunst Centrum : http://www.meesterschap.nu


"Ton den Hartog" <ton.den.hart...@tonh.net> wrote in message

news:3fec1926$0$327$e4fe...@news.xs4all.nl...

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 8:48:04 PM12/27/03
to
Ton den Hartog wrote:

>> document.getElementById('t').firstChild.nodeValue="Hello";
>
> That works. But what if I want a HTML element in the tag.

Not in the tag, in the _element_. You need to understand the difference
between these two before you do any DHTML.

> When I use "Hello<br>world" I get a LITERAL <br> in my
> browser-screen !! :-(

Of course. A text node is a _text_ node.

> How can I prevent that ?

Use the W3C-DOM. Quickhack:

if (typeof document != "undefined" && document.getElementById)
{
var o = document.getElementById("t");
if (o)
{
o.firstChild.nodeValue = "Hello";
o.appendChild(document.createElement("br"));
o.appendChild(document.createTextNode("world"));
}
}

> [Top post]

http://www.allmyfaqs.com/faq.pl?How_to_post


PointedEars

Jim Ley

unread,
Dec 27, 2003, 8:49:24 PM12/27/03
to
On Sun, 28 Dec 2003 02:41:35 +0100, "Ton den Hartog"
<ton.den.hart...@tonh.net> wrote:

>> document.getElementById('t').firstChild.nodeValue="Hello";
>
>That works. But what if I want a HTML element in the tag. When I use
>"Hello<br>world" I get a LITERAL <br> in my browser-screen !! :-( How can I
>prevent that ?

Then you have to do a lot more work and create a BR element and insert
it in the relevant place, then create a 2nd text node and add that
after it...

Much easier to just use innerHTML

if (document.getElementById) {
var t=document.getElementById('t');
if (t) {
t.innerHTML='hello<br>world';
}
}

Remember of course that no method works in 100% of browsers (and most
don't work in 60%) so it's always best to ensure that your content
works without javascript, and to ensure your javascript doesn't error
as much as possible.

Jim Ley

unread,
Dec 27, 2003, 8:55:37 PM12/27/03
to
On Sun, 28 Dec 2003 02:48:04 +0100, Thomas 'PointedEars' Lahn
<Point...@web.de> wrote:


>Use the W3C-DOM. Quickhack:
>
> if (typeof document != "undefined" && document.getElementById)
> {
> var o = document.getElementById("t");
> if (o)
> {

Generally it's a good idea if you're new to javascript to use

if (o) {

format, as you may well later be confused, see:

http://www.crockford.com/javascript/lint.html

> o.firstChild.nodeValue = "Hello";

You'll also want to check
if (o.firstChild) {
o.firstChild.nodeValue="Hello";
}
> o.appendChild(document.createElement("br"));

and
if (document.createElement && o.appendChild) {
o.appendChild(document.createElement("br"));
}

> o.appendChild(document.createTextNode("world"));

and

if (document.createTextNodet && o.appendChild) {
o.appendChild(document.createTextNode("world"));
}

Since some of the methods aren't available in all user agents.

Thomas 'PointedEars' Lahn

unread,
Dec 27, 2003, 10:25:11 PM12/27/03
to
Jim Ley wrote:

> Thomas 'PointedEars' Lahn wrote:
>>Use the W3C-DOM. Quickhack:
>>
>> if (typeof document != "undefined" && document.getElementById)
>> {
>> var o = document.getElementById("t");
>> if (o)
>> {
>
> Generally it's a good idea if you're new to javascript to use
>
> if (o) {
>
> format,

I do not agree. Clearly indicating where a statement begins, where it
ends, where a block starts and where it ends, helps to understand the
structure of code, especially for beginners.

> as you may well later be confused,

Nonsense.

> see:
>
> http://www.crockford.com/javascript/lint.html

You do not cite that as a reference for code style, do you?

I am not even convinced such a program is necessary or useful, since it
errors are best found at run time, when testing the code with different
hosts. Validating code with such only creates the temptation not to do
thorough testing "because the validator said it is OK."

>> o.firstChild.nodeValue = "Hello";
>
> You'll also want to check

> [...]


> Since some of the methods aren't available in all user agents.

Funny, you should know that I am usually the one who
recommends to check for everything before using it:

http://pointedears.de.vu/scripts/test/whatami

Maybe that's why I called this a *quickhack* ...


shaking the head,
PointedEars

Lasse Reichstein Nielsen

unread,
Dec 27, 2003, 10:51:04 PM12/27/03
to
"Ton den Hartog" <ton.den.hart...@tonh.net> writes:

PLEASE don't top post.

>> document.getElementById('t').firstChild.nodeValue="Hello";
>
> That works. But what if I want a HTML element in the tag. When I use
> "Hello<br>world" I get a LITERAL <br> in my browser-screen !! :-( How can I
> prevent that ?

If you want to use DOM methods;

var t = document.getElementById("t");
// clear content
while(t.hasChildNodes()) {
t.removeChild(t.lastChild);
}
// add new content:
t.appendChild(document.createTextNode("Hello"));
t.appendChild(document.createElement("br"));
t.appendChild(document.createTextNode("World"));

Search for the W3C DOM 2 specification to read more about dynamic
document manipulation.

DU

unread,
Dec 28, 2003, 1:14:47 PM12/28/03
to
Jim Ley wrote:

> On Sun, 28 Dec 2003 02:41:35 +0100, "Ton den Hartog"
> <ton.den.hart...@tonh.net> wrote:
>
>
>>> document.getElementById('t').firstChild.nodeValue="Hello";
>>
>>That works. But what if I want a HTML element in the tag. When I use
>>"Hello<br>world" I get a LITERAL <br> in my browser-screen !! :-( How can I
>>prevent that ?
>
>
> Then you have to do a lot more work and create a BR element and insert
> it in the relevant place, then create a 2nd text node and add that
> after it...
>
> Much easier to just use innerHTML

That's true: more [code] work, slower also (according to tests) with
HTML nodes created on the fly (1). I still do not think people should be
using innerHTML when they want to change a simple text node.

DU
(1) Even MSDN sets limits to the usefulness and performance of innerHTML
property, suggesting to use innerText when targeted nodes are text nodes.
More Performance Tips, October 4, 1999
"(...) By now, almost everyone knows that using element.innerHTML is
slow, slow, slow. To see just how slow it was, I made a final test page
that used innerHTML instead of innerText to insert "Text" into the cell.
This literally crushed performance."
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndude/html/dude100499.asp

Dr John Stockton

unread,
Dec 28, 2003, 10:56:52 AM12/28/03
to
JRS: In article <3fec0eb5$0$321$e4fe...@news.xs4all.nl>, seen in
news:comp.lang.javascript, Ton den Hartog <ton.den.hartog.removespam@ton
h.net> posted at Fri, 26 Dec 2003 11:34:27 :-

>Stupid basic question but I find it horribly imposible to find the answer
>elsewhere... :-(
>
>I want to have a piece of text in my HTML page and want to be able to change
>it in a Javascript function that is called from a button. I think I can use
>a
>
><div id="t"></div>
>
>for this ? Something like
>
>document.t.value="Hello"
>
>should change it into
>
><div id="t">Hello</div>


Read the FAQ of the newsgroup, as posted Mon/Fri. That is item 4.15,
and section 2.3 will also help you in the correct formatting of
newsgroup replies.


Important points are that this task - div changing - is likely to be
required more than once, and so is best encapsulated in a function (as
in the FAQ) and that the details are browser-dependent, which is another
reason for encapsulation.

Just code it as DynWrite("t", "Hello") which makes the meaning
perfectly clear.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<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.

DU

unread,
Dec 29, 2003, 11:44:37 AM12/29/03
to
Dr John Stockton wrote:
> JRS: In article <3fec0eb5$0$321$e4fe...@news.xs4all.nl>, seen in
> news:comp.lang.javascript, Ton den Hartog <ton.den.hartog.removespam@ton
> h.net> posted at Fri, 26 Dec 2003 11:34:27 :-
>
>>Stupid basic question but I find it horribly imposible to find the answer
>>elsewhere... :-(
>>
>>I want to have a piece of text in my HTML page and want to be able to change
>>it in a Javascript function that is called from a button. I think I can use
>>a
>>
>><div id="t"></div>
>>
>>for this ? Something like
>>
>>document.t.value="Hello"
>>
>>should change it into
>>
>><div id="t">Hello</div>
>
>
>
> Read the FAQ of the newsgroup, as posted Mon/Fri. That is item 4.15,
> and section 2.3 will also help you in the correct formatting of
> newsgroup replies.
>
>
> Important points are that this task - div changing - is likely to be
> required more than once, and so is best encapsulated in a function (as
> in the FAQ) and that the details are browser-dependent, which is another
> reason for encapsulation.
>
> Just code it as DynWrite("t", "Hello") which makes the meaning
> perfectly clear.
>


I have a problem with item 4.15 when one needs to change only the text
of a text node (and this is the case with the OP). Resorting to
innerHTML as clearly proposed by item 4.15 is not best, not the most
efficient and not complying with DOM 2 Core. A very wide majority of
users are using browsers which support perfectly each and all of
CharacterData methods. Therefore, IMO, the FAQ should be updated to
reflect this.

How about:

<div id="idDiv">previous text</div>

could be modified with the code:

if(document.getElementById("idDiv").firstChild &&
document.getElementById("idDiv").firstChild.nodeType == 3)
{
document.getElementById("idDiv").firstChild.nodeValue = "New text
replacing previous text";
};

DU

DU

unread,
Dec 29, 2003, 11:59:46 AM12/29/03
to
Jim Ley wrote:

[snipped]

>
>
> Generally it's a good idea if you're new to javascript to use
>
> if (o) {
>
> format, as you may well later be confused, see:
>
> http://www.crockford.com/javascript/lint.html
>
>

[snipped]

Jim, can you elaborate a bit of this brace format thing. I went to the
given url and only could find these words as *possibly* related to what
you're saying:

"Forbidden Blocks: (...) In JavaScript, blocks do not introduce a scope.
There is only function-scope. JavaScript's blocks confuse experienced
programmers and lead to errors."

I still do not understand how or why that particular format of creating
block would not make me confused; I don't understand.

I prefer to have the curly braces on the same column (and with indenting
nested ones) because this makes blocks of code easy to figure out (where
they start and where they end).
This issue may be not related to the OP but it sure is a matter of most
suitable coding practices.

This format:
if(boolean condition)
{
...
};
is easy to read.

That format:
if(boolean condition) {
...
};
does not help code readability.


DU

Lasse Reichstein Nielsen

unread,
Dec 29, 2003, 1:20:14 PM12/29/03
to
DU <drun...@hotREMOVETHISmail.com> writes:

> This format:
> if(boolean condition)
> {
> ...
> };
> is easy to read.
>
> That format:
> if(boolean condition) {
> ...
> };
> does not help code readability.

That is obviosuly completely personal. I have it exactly the opposite way.

I want the start of the block to be on the same line as the statement
keyword that uses it, not on the next line. It confuzes me when the
block seems to have no connection to the if statement.
The indentation takes care of showing what belongs to the block, so
I can just look at the end brace and find the preceding line with the
same indentation, to find the line where it starts.

Dr John Stockton

unread,
Dec 29, 2003, 3:34:35 PM12/29/03
to
JRS: In article <bspllv$7s6$1...@news.eusc.inter.net>, seen in
news:comp.lang.javascript, DU <drun...@hotREMOVETHISmail.com> posted
at Mon, 29 Dec 2003 11:44:37 :-

>
>I have a problem with item 4.15 when one needs to change only the text
>of a text node (and this is the case with the OP). Resorting to
>innerHTML as clearly proposed by item 4.15 is not best, not the most
>efficient and not complying with DOM 2 Core. A very wide majority of
>users are using browsers which support perfectly each and all of
>CharacterData methods. Therefore, IMO, the FAQ should be updated to
>reflect this.
>
>How about:
>
><div id="idDiv">previous text</div>
>
>could be modified with the code:
>
>if(document.getElementById("idDiv").firstChild &&
>document.getElementById("idDiv").firstChild.nodeType == 3)
>{
>document.getElementById("idDiv").firstChild.nodeValue = "New text
>replacing previous text";
>};


The purpose for which, IIRC, 4.15 was written was to enable the same
page to work in three major types of browser - for example, NS4.7,
MSIE4, and later. It turned out that the NS4.7 case, while IIRC
soluble, was difficult to deal with, in the matter of explaining
when/where a writeable region could be planted; it has been dropped.

Your code appears grievously defective, in that it works only in
browsers with getElementbyID, and where there is a first child of type
3; if there is no such child it fails silently, and if there is no
getElementbyID it crashes.

If put in the FAQ, any limitations need to be clearly noted, especially
for silent failure.


Moreover, one should not recommend to others code such as the above.
The code should be used by the modular form Func(Dest, String) ; with
the workings nicely encapsulated in Func, which can be defined earlier
in the page or in an include file.


But if your code is included in such a function as 4.15 gives, in a
manner such that it can never fail silently, then I can readily believe
that it could be useful.


Web pages need to be designed, by US & UK law where applicable, to be
adequately accessible to the physically disabled. They should also be
designed to be accessible to the fiscally disabled, for example in the
Third World and in the American backwoods, where it may be necessary to
continue with older systems. Admittedly IIRC the US Act, judged by
title, only favours disabled Americans; but the UK Act is not similarly
restrictive.


... I don't want details; but do other EU countries have legislation
similar to the UK Disability Discrimination Act(s)?

Dr John Stockton

unread,
Dec 29, 2003, 3:48:22 PM12/29/03
to
JRS: In article <ekunjx...@hotpop.com>, seen in
news:comp.lang.javascript, Lasse Reichstein Nielsen <l...@hotpop.com>
posted at Mon, 29 Dec 2003 19:20:14 :-

>
>I want the start of the block to be on the same line as the statement
>keyword that uses it, not on the next line. It confuzes me when the
>block seems to have no connection to the if statement.
>The indentation takes care of showing what belongs to the block, so
>I can just look at the end brace and find the preceding line with the
>same indentation, to find the line where it starts.


One needs first to decide exactly what the indentation is going to be
used for.

IMHO, manual indentation cannot be used to show structure in a page that
is being written; it can only show intended structure, which is a
distinct concept.

If the page is indented by a program, which understands sufficient of
the rules of the language but nothing of the author's intent, then it
shows the actual structure. This is very useful, if achievable (I wrote
a Pascal program to do it for Pascal); if the author sees, where no
indentation was expected, either positive or negative indentation, then
he has received useful information.

Once the page is structurally correct, of course, the above layout
algorithms come into agreement.

My own preference is for the indentation of the first inky character of
a line to depend only on the content of previous lines, and to be one
level for each open structure plus one level if the new line breaks a
statement. But that is partly the result of years of using layout tools
that give that (I wrote an earlier Algol version that indented Algol
thusly, *and* put one null before and three nulls after every CRLF on
the output eight-hole tape).

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
<URL:http://www.merlyn.demon.co.uk/clpb-faq.txt> RAH Prins : c.l.p.b mFAQ;
<URL:ftp://garbo.uwasa.fi/pc/link/tsfaqp.zip> Timo Salmi's Turbo Pascal FAQ.

DU

unread,
Dec 30, 2003, 11:46:19 AM12/30/03
to
Dr John Stockton wrote:

Yes. I intentionally do not wish to write more javascript code to
support browsers which do not support getElementById. That's per webpage
[specification] requirements; that my policy - one day, people have
to/should/should be invited to/must upgrade. Now, roughly 96% of all
browsers in use out there support document.getElementById.

, and where there is a first child of type
> 3; if there is no such child it fails silently,

If there is no first child of type 3, then it means there is no text
node as first child and the function should end there. That's on purpose.

and if there is no
> getElementbyID it crashes.
>

It will not work for about 4% of browsers in use out there. In which
case, normal accessibility fallback mechanisms should take over. In any
case of webpage design, checking how a page behaves, functions, manages
without javascript support enabled is a sane and necessary task to do.

> If put in the FAQ, any limitations need to be clearly noted, especially
> for silent failure.
>
>

I kinda agree with you but I think the FAQ should not be an endless
tutorial on how to do professional webpages. There is a limit to what
should be answered, explained, described in a FAQ. People are annoyed by
lengthy FAQ. There is no limitations set or any kind of implicit or
explicit constraint in letting users search for answers by themselves:
searching tutorials, columns, lurking in newsgroups, etc..
Whatever item 4.15 uses, there will be silent failures for any kind of
code (e.g. MSN-TV does not support innerHTML).

> Moreover, one should not recommend to others code such as the above.

I was merely submitting the relevant working code in a discussion
newsgroup. As far as I'm concerned, item 4.15 as written (explanations
and code) is not easy to understand, is not recommendable as it is and
is definitively improvable.

> The code should be used by the modular form Func(Dest, String) ; with
> the workings nicely encapsulated in Func, which can be defined earlier
> in the page or in an include file.
>

Modularizing the code was not the main point of my reply. Of course,
modularization of code is always better and brings lots of benefits. And
modularization of my code would be very easy to do. If item 4.15 aims at
educating newbies on proper and best coding practices, then it should
offer an answer where the code is modularized too: I don't even see that
right now. Do you?

>
> But if your code is included in such a function as 4.15 gives,

I don't see a clear, easy to grasp, straightforward, easy-to-implement
function in 4.15. I think 4.15 should be entirely re-written.

in a
> manner such that it can never fail silently, then I can readily believe
> that it could be useful.
>

It is not my goal to write a function that never fails silently. I think
such goal for any kind of script function is unrealistic to begin with.

DU

Dr John Stockton

unread,
Dec 30, 2003, 3:25:25 PM12/30/03
to
JRS: In article <bssa4q$51g$1...@news.eusc.inter.net>, seen in

news:comp.lang.javascript, DU <drun...@hotREMOVETHISmail.com> posted
at Tue, 30 Dec 2003 11:46:19 :-
>Dr John Stockton wrote:

>> Your code appears grievously defective, in that it works only in
>> browsers with getElementbyID
>
>Yes. I intentionally do not wish to write more javascript code to
>support browsers which do not support getElementById. That's per webpage
>[specification] requirements; that my policy - one day, people have
>to/should/should be invited to/must upgrade. Now, roughly 96% of all
>browsers in use out there support document.getElementById.

You may choose to do that in your own work - it might well be considered
in breach of the spirit of ADA / DAA, where applicable - but it is not
right to lead others to do it without warning of limitations known to
you.


>, and where there is a first child of type
>> 3; if there is no such child it fails silently,
>
>If there is no first child of type 3, then it means there is no text
>node as first child and the function should end there. That's on purpose.

The programmer, then, has attempted to do the impossible. A warning of
some sort needs to be given; it may well be that the string-writing is
essential but inadvertently mis-aimed. A silent failure is too easily
missed on test, and is liable to be missed in real use.


> There is a limit to what
>should be answered, explained, described in a FAQ. People are annoyed by
>lengthy FAQ. There is no limitations set or any kind of implicit or
>explicit constraint in letting users search for answers by themselves:
>searching tutorials, columns, lurking in newsgroups, etc..

The whole point of a newsgroup FAQ is to make that unnecessary. By
searching, one can find any number of answers, many of which more-or-
less work, usually. In an actively-edited newsgroup FAQ, one finds
reviewed good-practice answers; one can expect any limitations to be
noted.

>Whatever item 4.15 uses, there will be silent failures for any kind of
>code (e.g. MSN-TV does not support innerHTML).

Jim? Does that give a silent failure? If do, can that be fixed, or is
MSN-TV an unreasonably inadequate system?


>> The code should be used by the modular form Func(Dest, String) ; with
>> the workings nicely encapsulated in Func, which can be defined earlier
>> in the page or in an include file.
>>
>
>Modularizing the code was not the main point of my reply. Of course,
>modularization of code is always better and brings lots of benefits. And
>modularization of my code would be very easy to do. If item 4.15 aims at
>educating newbies on proper and best coding practices, then it should
>offer an answer where the code is modularized too: I don't even see that
>right now. Do you?

Indeed so; one executes the code once (so it need not be made into a
function) and after that one just calls DynWrite('DivID', 'String') when
needed.


>> But if your code is included in such a function as 4.15 gives,
>
>I don't see a clear, easy to grasp, straightforward, easy-to-implement
>function in 4.15. I think 4.15 should be entirely re-written.

When upgrading my <URL:http://www.merlyn.demon.co.uk/holidays.htm>, I
copy'n'pasted the code from the FAQ into the page, correcting only the
superfluous first space character. Using a div and a DynWrite call as
described immediately above in the FAQ, it worked immediately. I don't
see what greater ease could be wished for.

One does, I grant, need to get used to Jim's style of writing the bodies
of FAQ entries; but that applied to any technical document not
professionally sub-edited.

>in a
>> manner such that it can never fail silently, then I can readily believe
>> that it could be useful.
>>
>
>It is not my goal to write a function that never fails silently. I think
>such goal for any kind of script function is unrealistic to begin with.


Perhaps it is impossible to achieve silent failure in all cases. But
predictable silent failure should never be permitted. Consider the case
of a silently failing attempt to insert "NOT" into the div here -

<p>You must <div ID=X2334>now</div> do that!

DU

unread,
Dec 31, 2003, 12:17:24 PM12/31/03
to
Dr John Stockton wrote:

> JRS: In article <bssa4q$51g$1...@news.eusc.inter.net>, seen in
> news:comp.lang.javascript, DU <drun...@hotREMOVETHISmail.com> posted
> at Tue, 30 Dec 2003 11:46:19 :-
>
>>Dr John Stockton wrote:
>
>
>>>Your code appears grievously defective, in that it works only in
>>>browsers with getElementbyID
>>
>>Yes. I intentionally do not wish to write more javascript code to
>>support browsers which do not support getElementById. That's per webpage
>>[specification] requirements; that my policy - one day, people have
>>to/should/should be invited to/must upgrade. Now, roughly 96% of all
>>browsers in use out there support document.getElementById.
>
>
> You may choose to do that in your own work - it might well be considered
> in breach of the spirit of ADA / DAA,

ADA / DAA: I'm getting more and more annoyed by acronyms and
abbreviations of all sorts here and there. What do these refer to?

Browsers which do not support getElementById are as far I'm concerned
somewhat defective, are not compliant with W3C web standards and
certainly need to be upgraded.

where applicable - but it is not
> right to lead others to do it without warning of limitations known to
> you.
>
>

Can you elaborate on what would be in your opinion a sufficient warning
of limitation in such script? Can you give a full example of what you
have been supporting, defending?

>
>>, and where there is a first child of type
>>
>>>3; if there is no such child it fails silently,
>>
>>If there is no first child of type 3, then it means there is no text
>>node as first child and the function should end there. That's on purpose.
>
>
> The programmer, then, has attempted to do the impossible.

I don't understand what you wrote here and why you wrote that. The
function checks the first node and if it is not a text node, then
nothing is done because nothing should be done in such case. You say my
function fails: I would say it works precisely and accordingly. <shrug>

A warning of
> some sort needs to be given; it may well be that the string-writing is
> essential but inadvertently mis-aimed. A silent failure is too easily
> missed on test, and is liable to be missed in real use.
>

If document.getElementById is not supported, then what are you proposing
should be the warning? and how to report such warning to the user? via
an alert?

>
>
>
>
>>There is a limit to what
>>should be answered, explained, described in a FAQ. People are annoyed by
>>lengthy FAQ. There is no limitations set or any kind of implicit or
>>explicit constraint in letting users search for answers by themselves:
>>searching tutorials, columns, lurking in newsgroups, etc..
>
>
> The whole point of a newsgroup FAQ is to make that unnecessary.

Could you have a look at that newsgroup FAQ, in particular the whole
section 3 then? Are you suggesting that we should remove section 3 of
the FAQ?
May I repeat here what I already wrote in this thread:

Further reading:
Nodes:
http://www.quirksmode.org/dom/intro.html#nodes

The Document Object Model (DOM):
The Simple Document's Diagram
http://webreference.com/js/column40/drawsimple.html
(Reading the entire article is best)

By
> searching, one can find any number of answers, many of which more-or-
> less work, usually. In an actively-edited newsgroup FAQ, one finds
> reviewed good-practice answers; one can expect any limitations to be
> noted.
>
>
>
>
>>Whatever item 4.15 uses, there will be silent failures for any kind of
>>code (e.g. MSN-TV does not support innerHTML).
>
>
> Jim? Does that give a silent failure? If do, can that be fixed, or is
> MSN-TV an unreasonably inadequate system?
>
>

Why stop to MSN-TV? How about NS 4.x? How about IE 4? These 2 browsers
were designed more than 7 years ago. And there are a lot of free,
modern, much better, available alternatives to these browsers or much
newer versions. Why is it that script code should be longer/bigger/more
bloated because it should always try to cater for these old and
non-compliant browsers which do not represent 1% of all users out there?

Checking for object support, method support, property support makes
sense when such support is not universal or is known to be partially
supported in current browsers in use. getElementById is widely supported
in recent browsers; it's not supported in old browsers. Being exhaustive
in cases such as getElementById equate to creating bloated code and
conforting people into not upgrading to a W3C web standards compliant
browser.

>
>>>The code should be used by the modular form Func(Dest, String) ; with
>>>the workings nicely encapsulated in Func, which can be defined earlier
>>>in the page or in an include file.
>>>
>>
>>Modularizing the code was not the main point of my reply. Of course,
>>modularization of code is always better and brings lots of benefits. And
>>modularization of my code would be very easy to do. If item 4.15 aims at
>>educating newbies on proper and best coding practices, then it should
>>offer an answer where the code is modularized too: I don't even see that
>>right now. Do you?
>
>
> Indeed so; one executes the code once (so it need not be made into a
> function) and after that one just calls DynWrite('DivID', 'String') when
> needed.
>

Are you actually saying that the given code in item 4.15 is currently
modularized?

>
>
>>>But if your code is included in such a function as 4.15 gives,
>>
>>I don't see a clear, easy to grasp, straightforward, easy-to-implement
>>function in 4.15. I think 4.15 should be entirely re-written.
>
>
> When upgrading my <URL:http://www.merlyn.demon.co.uk/holidays.htm>, I
> copy'n'pasted the code from the FAQ into the page, correcting only the
> superfluous first space character. Using a div and a DynWrite call as
> described immediately above in the FAQ, it worked immediately. I don't
> see what greater ease could be wished for.
>
> One does, I grant, need to get used to Jim's style of writing the bodies
> of FAQ entries; but that applied to any technical document not
> professionally sub-edited.
>
>
>>in a
>>
>>>manner such that it can never fail silently, then I can readily believe
>>>that it could be useful.
>>>
>>
>>It is not my goal to write a function that never fails silently. I think
>>such goal for any kind of script function is unrealistic to begin with.
>
>
>
> Perhaps it is impossible to achieve silent failure in all cases. But
> predictable silent failure should never be permitted.

Can you give an example (script code) of what would be acceptable within
your line of thinking (minimize silent failure occurences) in cases such
as getElementById?

Consider the case
> of a silently failing attempt to insert "NOT" into the div here -
>
> <p>You must <div ID=X2334>now</div> do that!
>
>

I would use an alert call for such scenario or server side include... it
would depend on the whole page context.

DU

Dr John Stockton

unread,
Dec 31, 2003, 3:19:04 PM12/31/03
to
JRS: In article <bsv0b2$1df$1...@news.eusc.inter.net>, seen in

news:comp.lang.javascript, DU <drun...@hotREMOVETHISmail.com> posted
at Wed, 31 Dec 2003 12:17:24 :-
>Dr John Stockton wrote:

>> You may choose to do that in your own work - it might well be considered
>> in breach of the spirit of ADA / DAA,
>
>ADA / DAA: I'm getting more and more annoyed by acronyms and
>abbreviations of all sorts here and there. What do these refer to?

You are an American programmer and you do not know of ADA, your own
applicable legislation? DAA is a typo for DDA, the corresponding UK
Act.


>Browsers which do not support getElementById are as far I'm concerned
>somewhat defective, are not compliant with W3C web standards and
>certainly need to be upgraded.
>
>where applicable - but it is not
>> right to lead others to do it without warning of limitations known to
>> you.
>
>Can you elaborate on what would be in your opinion a sufficient warning
>of limitation in such script? Can you give a full example of what you
>have been supporting, defending?


Read more thoughtfully; we are discussing what you wrote in the
newsgroup; and the warning should have been written in the article.

"This code fails, without giving any indication, in browsers without
getElementbyID." would have sufficed. Or, in the code,
else alert("WriteFail")
to go with the 'if'.


Code should preferably be infallible, and therefore incapable of giving
warnings or errors. Otherwise, instead of failing silently, give an
alert, a pop-op, or other visible indication.


>>>, and where there is a first child of type
>>>
>>>>3; if there is no such child it fails silently,
>>>
>>>If there is no first child of type 3, then it means there is no text
>>>node as first child and the function should end there. That's on purpose.

But the programmer has attempted to write there. Therefore, the output
is not as intended; error.


>> The programmer, then, has attempted to do the impossible.
>
>I don't understand what you wrote here and why you wrote that. The
>function checks the first node and if it is not a text node, then
>nothing is done because nothing should be done in such case. You say my
>function fails: I would say it works precisely and accordingly. <shrug>

If nothing should be done, then code should not be executed.

> A warning of
>> some sort needs to be given; it may well be that the string-writing is
>> essential but inadvertently mis-aimed. A silent failure is too easily
>> missed on test, and is liable to be missed in real use.
>>
>
>If document.getElementById is not supported, then what are you proposing
>should be the warning? and how to report such warning to the user? via
>an alert?

Perhaps inelegant; but better than nothing. If the page design really
needs that facility, it may be better to show a different page.


>>>There is a limit to what
>>>should be answered, explained, described in a FAQ. People are annoyed by
>>>lengthy FAQ. There is no limitations set or any kind of implicit or
>>>explicit constraint in letting users search for answers by themselves:
>>>searching tutorials, columns, lurking in newsgroups, etc..
>>
>>
>> The whole point of a newsgroup FAQ is to make that unnecessary.
>
>Could you have a look at that newsgroup FAQ, in particular the whole
>section 3 then? Are you suggesting that we should remove section 3 of
>the FAQ?

No; section 3 is useful because it holds selected references; ones that
Jim has presumably looked at and considered to be worthwhile. In going
to those references, one is not searching; one has been told where to
look.


>Why stop to MSN-TV? How about NS 4.x? How about IE 4? These 2 browsers
>were designed more than 7 years ago. And there are a lot of free,
>modern, much better, available alternatives to these browsers or much
>newer versions. Why is it that script code should be longer/bigger/more
>bloated because it should always try to cater for these old and
>non-compliant browsers which do not represent 1% of all users out there?

That's rather a Merkin attitude.

While the latest browser software does not require purchase, it uses
machine resources which may not be available on older machines. In the
third world, and even in the American boonies, such resources cannot
always be afforded.

>> Indeed so; one executes the code once (so it need not be made into a
>> function) and after that one just calls DynWrite('DivID', 'String') when
>> needed.
>>
>
>Are you actually saying that the given code in item 4.15 is currently
>modularized?

Not that it is itself modularised; but that it supports modular coding.
It defines a function, such that subsequently the coder has only to say
what is to be done (DynWrite), where (id), and with what (S). Once the
coder has caused the code in the box to be executed, he need have no
further concern with the mechanism.


Your own code must be executed everywhere that a string is written into
a div; AFAICS, it has only two varying parts, the destination and the
string, and so it could be used as the body of, say,
function DUwrite(id, S) { ... }

Now the aforementioned alert can cheaply be
alert("Writefail\n"+S)

Naive programmers, and we see plenty of those here, have little
understanding of the proper use of functions; it is well to set a good
example.

>Can you give an example (script code) of what would be acceptable within
>your line of thinking (minimize silent failure occurences) in cases such
>as getElementById?
>
> Consider the case
>> of a silently failing attempt to insert "NOT" into the div here -
>>
>> <p>You must <div ID=X2334>now</div> do that!
>>
>>
>
>I would use an alert call for such scenario or server side include... it
>would depend on the whole page context.

Why need I give an example when you obviously can do so yourself?

In avoiding silent failure, there are two alternatives : avoid silence,
or avoid failure.

Jim Ley

unread,
Jan 2, 2004, 8:17:07 AM1/2/04
to
On Tue, 30 Dec 2003 20:25:25 +0000, Dr John Stockton
<sp...@merlyn.demon.co.uk> wrote:

>>Whatever item 4.15 uses, there will be silent failures for any kind of
>>code (e.g. MSN-TV does not support innerHTML).
>
>Jim? Does that give a silent failure? If do, can that be fixed, or is
>MSN-TV an unreasonably inadequate system?

The method to detect that an assignment to innerHTML isn't easy and a
little confusing*, so reliably returning true/false on it is certainly
beyond a FAQ answer unfortunately 4.15 has already been simplified
once, it might be nice to simplify it down even further.

Silent failures are always going to happen in scripting I think, and
it's a good idea to try and author with this in mind, rather than try
an cope with every failure to a non-silent one.

>One does, I grant, need to get used to Jim's style of writing the bodies
>of FAQ entries; but that applied to any technical document not
>professionally sub-edited.

I've not been around much in the last year (I was travelling for the
first 8 months and have since been trying to make the bank manager
smile at me again.) and the FAQ certainly needs updating, I'm busy
right now for a couple more months.

I am however more than willing to give anyone here with a reputation
in the group a login to the box, and therefore the ability to edit the
FAQ, including running the wscript script I currently use. Of course
an editor would be good. The editors I do know say I have some of the
worst grammar they've ever seen, so I'm pretty sure I'm not the best
person.

Cheers,

Jim.

[*] My brief thoughts are:

foo="<sTroNg >test</sTronG >";
someDiv.innerHTML=foo;
innerHTMLWorks= !(foo==someDiv.innerHTML);

and

'<strong id=chicken>test</strong>
followed by a getElementById or equivalent.

but I'm sure both could be shown false in certain circumstances.

Dr John Stockton

unread,
Jan 2, 2004, 2:39:08 PM1/2/04
to
JRS: In article <3ff4b975...@news.cis.dfn.de>, seen in
news:comp.lang.javascript, Jim Ley <j...@jibbering.com> posted at Fri, 2
Jan 2004 13:17:07 :-

>On Tue, 30 Dec 2003 20:25:25 +0000, Dr John Stockton
><sp...@merlyn.demon.co.uk> wrote:
>
>>>Whatever item 4.15 uses, there will be silent failures for any kind of
>>>code (e.g. MSN-TV does not support innerHTML).
>>
>>Jim? Does that give a silent failure? If do, can that be fixed, or is
>>MSN-TV an unreasonably inadequate system?
>
>The method to detect that an assignment to innerHTML isn't easy and a
>little confusing*, so reliably returning true/false on it is certainly
>beyond a FAQ answer unfortunately 4.15 has already been simplified
>once, it might be nice to simplify it down even further.


if (document.all && !document.getElementById) {
document.getElementById = function(id) { // Randy
return document.all[id] } }

was posted here within the last few months. Does it provide a reliable
alternative?

>Silent failures are always going to happen in scripting I think, and
>it's a good idea to try and author with this in mind, rather than try
>an cope with every failure to a non-silent one.


I don't see how one can in general cope with computed material that may
not appear, unless some sort of warning is shown.

Can one deal with the matter reliably along the lines of

<div ID=test align=center><BIG> <!-- HTML -->
So long as this text remains, the provision for writing
necessary material to this page cannot be presumed to be
working.
<br>YOU HAVE BEEN WARNED</BIG></div>

SomeWrite("ID", "All seems well") // javascript

?

OTOH, in a case like my holidays.htm, which has "Tabulate" buttons with
a definite implication that they should do something, perhaps no more is
needed than an indication of where something should happen.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

HikksNotAtHome

unread,
Jan 2, 2004, 7:37:06 PM1/2/04
to
In article <ZlQqVqAcjc9$Ew...@merlyn.demon.co.uk>, Dr John Stockton
<sp...@merlyn.demon.co.uk> writes:

>>
>>The method to detect that an assignment to innerHTML isn't easy and a
>>little confusing*, so reliably returning true/false on it is certainly
>>beyond a FAQ answer unfortunately 4.15 has already been simplified
>>once, it might be nice to simplify it down even further.
>
>
> if (document.all && !document.getElementById) {
> document.getElementById = function(id) { // Randy
> return document.all[id] } }
>
>was posted here within the last few months. Does it provide a reliable
>alternative?

While I am gracious to have my name mentioned in it, I can't claim credit for
it. It came from the metallusions website, I only stumbled on it (IIRC, someone
else pointed me to it).

<URL: http://www.metalusions.com/backstage/articles/8/ />


But all the code does is make getElementById semi-work in IE4 by returning a
reference to document.all[element] when document.getElementById(element) is
called.
I think what Jim is referring to is attempting to test that inserting innerHTML
actually works is nearly impossible to do.
The closest he came was to suggest comparing an elements innerHTML (after
attempting to change it) to what you tried to insert. Consider:


function insertHTML(){
document.getElementById('myDiv').innerHTML =
"<table><tr></td>Some Sample innerHTML</td></tr></table>";
document.myForm.myTextArea.value =
document.getElementById('myDiv').innerHTML;
}

<div id="myDiv"></div>
<form name="myForm">
<textarea name="myTextArea" rows="5" cols="80"></textarea>
</form>

IE6.0 gives:

<TABLE>
<TBODY>
<TR></TD>Some Sample innerHTML</TD></TR></TBODY></TABLE>

With those line breaks.

Mozilla Firebird 0.7 gives:

<table><tbody><tr>Some Sample innerHTML</tr></tbody></table>

With no line breaks but no TD tags.

Neither of which will match the original code. The only way to try to match
them is to check every known browser, see what it puts in the textarea, and
then do browser detection to try to find out what browser so you can determine
what string it should match.

Another alternative might be to compare the previous innerHTML to the latter
innerHTML though. If they don't match, then it didn't work:

function insertHTML(elem,newHTML){
tempVar = document.getElementById(elem).innerHTML;
document.getElementById(elem).innerHTML = newHTML;
if (tempVar == document.getElementById(elem).innerHTML) {alert('It failed')}
}

Then, its comparing its own rendering against its own rendering. If they match,
then the attempt to change it failed.

Thoughts?
--
Randy

HikksNotAtHome

unread,
Jan 2, 2004, 7:41:38 PM1/2/04
to
In article <20040102193706...@mb-m10.aol.com>,
hikksno...@aol.com (HikksNotAtHome) writes:

>Another alternative might be to compare the previous innerHTML to the latter
>innerHTML though. If they don't match, then it didn't work:

That should read "If they match, then it didn't work"

--
Randy

Lasse Reichstein Nielsen

unread,
Jan 2, 2004, 7:59:25 PM1/2/04
to
hikksno...@aol.com (HikksNotAtHome) writes:

> While I am gracious to have my name mentioned in it, I can't claim
> credit for it. It came from the metallusions website, I only
> stumbled on it (IIRC, someone else pointed me to it).

It is a fairly obvious approach. I have several different versions
of user-defined getElementById methods (and addEventListener is a
personal favorite too).

> Another alternative might be to compare the previous innerHTML to the latter
> innerHTML though. If they don't match, then it didn't work:

You can also (safely, I think) assume that a value gotten from the
innerHTML property can be put back in and give the same result.

> function insertHTML(elem,newHTML){
> tempVar = document.getElementById(elem).innerHTML;
> document.getElementById(elem).innerHTML = newHTML;
> if (tempVar == document.getElementById(elem).innerHTML) {alert('It failed')}
> }

This only thsts the ability to change, not to change correctly :)
It is probably enough, but you can do a test like this;

<div id="dummy">some <em class='dummyClass'>dummy</em> text</div>
<script type="text/javascript">
var elem = document.getElementById("dummy");
var oldIH = dummy.innerHTML;
dummy.innerHTML = "some <strong>other</strong> text";
var newIH = dummy.innerHTML;
dummy.innerHTML = oldIH:
var oldIH2 = dummy.innerHTML;
var IHworks = oldIH != newIH && oldIH == oldIH2;
</script>
If setting and reading innerHTML works, this is even non-destructive.

HikksNotAtHome

unread,
Jan 2, 2004, 8:47:32 PM1/2/04
to
In article <ad557s...@hotpop.com>, Lasse Reichstein Nielsen <l...@hotpop.com>
writes:

>> Another alternative might be to compare the previous innerHTML to the
>latter
>> innerHTML though. If they don't match, then it didn't work:
>
>You can also (safely, I think) assume that a value gotten from the
>innerHTML property can be put back in and give the same result.

Theoretically, and probably realistically, it should.

>> function insertHTML(elem,newHTML){
>> tempVar = document.getElementById(elem).innerHTML;
>> document.getElementById(elem).innerHTML = newHTML;
>> if (tempVar == document.getElementById(elem).innerHTML) {alert('It
>failed')}
>> }
>
>This only thsts the ability to change, not to change correctly :)
>It is probably enough, but you can do a test like this;

It is enough. The test is only to see if the browser supports changing the
innerHTML, not to see whether it renders it correctly or not. Your test almost
reminds me of the safecracker who wanted to use a nuclear bomb to open a safe
s/he bought on Ebay.
--
Randy

Jim Ley

unread,
Jan 3, 2004, 8:05:18 AM1/3/04
to
On 03 Jan 2004 00:37:06 GMT, hikksno...@aol.com (HikksNotAtHome)
wrote:

>Neither of which will match the original code. The only way to try to match
>them is to check every known browser, see what it puts in the textarea, and
>then do browser detection to try to find out what browser so you can determine
>what string it should match.

I was relying on the fact it would be a normalised source, so by
putting in mixed case element names, and extra whitespace in the
elements I was relying that if innerHTML wasn't known, then it would
be the same (it would just be a new property on the DOM element) but
it if it was known it was normalised away.

Jim.

Jim Ley

unread,
Jan 3, 2004, 8:07:02 AM1/3/04
to
On Sat, 03 Jan 2004 01:59:25 +0100, Lasse Reichstein Nielsen
<l...@hotpop.com> wrote:

>You can also (safely, I think) assume that a value gotten from the
>innerHTML property can be put back in and give the same result.

The same would be true of .chicken or a read only innerHTML that
resulted in no change afterwards. What we want to know is if our
content ended up on the page.

Lasse Reichstein Nielsen

unread,
Jan 3, 2004, 8:50:16 AM1/3/04
to
j...@jibbering.com (Jim Ley) writes:

> The same would be true of .chicken or a read only innerHTML that
> resulted in no change afterwards. What we want to know is if our
> content ended up on the page.

Ah, Doh. *slaps forehead*. Yes, simply testing that you can write
to it, is not sufficient.

You assume that the HTML is normalized when passed through innerHTML.
That is a fair assumption, and correct for the current browsers.

Another method could be to create an element with an id, and then check
whether it becomes part of the document with document.getElementById
(or fallbacks, e.g., document.all, as usual).

HikksNotAtHome

unread,
Jan 3, 2004, 1:59:07 PM1/3/04
to
In article <3ff6bd9...@news.cis.dfn.de>, j...@jibbering.com (Jim Ley)
writes:

>
>I was relying on the fact it would be a normalised source, so by
>putting in mixed case element names, and extra whitespace in the
>elements I was relying that if innerHTML wasn't known, then it would
>be the same (it would just be a new property on the DOM element) but
>it if it was known it was normalised away.

Just for my own curiosity, do you see any problems with the function I wrote to
check to see if it works?

function insertHTML(elem,newHTML){
tempVar = document.getElementById(elem).innerHTML;
document.getElementById(elem).innerHTML = newHTML;
if (tempVar == document.getElementById(elem).innerHTML) {alert('It failed')}
}

Maybe a different alert message (or another notifying mechanism). I left out
the object detection that should obviously go with it though.
--
Randy

Lasse Reichstein Nielsen

unread,
Jan 3, 2004, 6:16:09 PM1/3/04
to
hikksno...@aol.com (HikksNotAtHome) writes:

> Just for my own curiosity, do you see any problems with the function
> I wrote to check to see if it works?

I can see the same problem he pointed out in my attempt :)

> function insertHTML(elem,newHTML){
> tempVar = document.getElementById(elem).innerHTML;
> document.getElementById(elem).innerHTML = newHTML;
> if (tempVar == document.getElementById(elem).innerHTML) {alert('It failed')}
> }

Change "innerHTML" to "chicken" and it appears to work. That is, it only
tests whether there is a writeable property, not whether assigning to it
changes the document structure.
It would succeede in Netscape 4, if the getElementById had worked.

Dr John Stockton

unread,
Jan 3, 2004, 1:58:50 PM1/3/04
to
JRS: In article <3ff6be1...@news.cis.dfn.de>, seen in
news:comp.lang.javascript, Jim Ley <j...@jibbering.com> posted at Sat, 3
Jan 2004 13:07:02 :-

>On Sat, 03 Jan 2004 01:59:25 +0100, Lasse Reichstein Nielsen
><l...@hotpop.com> wrote:
>
>>You can also (safely, I think) assume that a value gotten from the
>>innerHTML property can be put back in and give the same result.
>
>The same would be true of .chicken or a read only innerHTML that
>resulted in no change afterwards. What we want to know is if our
>content ended up on the page.

We want to know if the previous visible content (if any) is removed, if
new content appears, and if new content looks as expected; or if an
error message appears.

We, as authors, can never know, since writing for an unknown browser is
a one-way process. Only if we can run the same version of the same
browser and test it ourselves can we really know.

Our code can never know all of the above; it cannot detect a fatal
error, it cannot read the screen, and it cannot detect a systematic
delusion that the required property is spelt InnerHTML.


ISTM that

<div ID=X><FONT color=red>NO GOOD</font></div>
That should read "All seems well", in lime.

<script ... >
DynWrite('X', '<FONT color=lime>All seems well</font>')

should enable the user to tell whether things are at least to some
extent working.

--

HikksNotAtHome

unread,
Jan 3, 2004, 6:50:32 PM1/3/04
to
In article <isjsaa...@hotpop.com>, Lasse Reichstein Nielsen <l...@hotpop.com>
writes:

>Change "innerHTML" to "chicken" and it appears to work. That is, it only


>tests whether there is a writeable property, not whether assigning to it
>changes the document structure.
>It would succeede in Netscape 4, if the getElementById had worked.

<sigh> CRAP! </sigh>

I knew I was missing something.........
--
Randy

Dr John Stockton

unread,
Jan 4, 2004, 8:33:07 AM1/4/04
to
JRS: In article <20040103135907...@mb-m27.aol.com>, seen in
news:comp.lang.javascript, HikksNotAtHome <hikksno...@aol.com>
posted at Sat, 3 Jan 2004 18:59:07 :-

>Just for my own curiosity, do you see any problems with the function I wrote to
>check to see if it works?
>
>function insertHTML(elem,newHTML){
>tempVar = document.getElementById(elem).innerHTML;
>document.getElementById(elem).innerHTML = newHTML;
>if (tempVar == document.getElementById(elem).innerHTML) {alert('It failed')}
>}

One needs also to check that it fails correctly!

Consider
insertHTML('F', 'OK')
insertHTML('F', 'OK')
The second one will report failure. A script could well have an error-
message Div, writing 'OK' or a fault-report to it for each iteration.

I get no alert on once executing a version of the above with innerHTML
changed to innnerHTML, which implies that the pre-existence of innerHTML
must be tested.

One might read the existing innerHTML, add a character to it, write it,
and read back; that seems OK even if innerHTML is undefined.

0 new messages