Cannot write to the DOM

R

RH

I'm a newbie, and just starting to use javascript. I've written a small program that simply adds an element to an unordered list in the DOM:

<body>
<form>
<input type="text" name="filePath" size="100" />
<button id="add_button">Add Element</button>
</form>
<ul id="test"></ul>
<script language="JavaScript" type="text/javascript" src="viewer.js">
</script>
</body>

script in viewer.js:

window.onload = init();

function init() {
var button = document.getElementById("add_button");
button.onclick = create;
}


function create() {
// create the element in the DOM
var listItemViewer = document.getElementById("test");

var test = document.createElement("li");
test.innerHTML = "test list item";
listItemViewer.appendChild(test);
}

If I run it and click the add button, it flashes the "test list item" on the screen - if I single step it through the debugger, it shows that it puts the element in the DOM at the end of the create() function, but then it gets stripped out? Can anyone help me understand why this is happening?

Thanks,
 
T

Tim Streater

RH said:
I'm a newbie, and just starting to use javascript. I've written a small
program that simply adds an element to an unordered list in the DOM:

<body>
<form>
<input type="text" name="filePath" size="100" />
<button id="add_button">Add Element</button>
</form>
<ul id="test"></ul>
<script language="JavaScript" type="text/javascript" src="viewer.js">
</script>
</body>

script in viewer.js:

window.onload = init();

function init() {
var button = document.getElementById("add_button");
button.onclick = create;
}


function create() {
// create the element in the DOM
var listItemViewer = document.getElementById("test");

var test = document.createElement("li");
test.innerHTML = "test list item";
listItemViewer.appendChild(test);
}

If I run it and click the add button, it flashes the "test list item" on the
screen - if I single step it through the debugger, it shows that it puts the
element in the DOM at the end of the create() function, but then it gets
stripped out? Can anyone help me understand why this is happening?

Thanks,


Your button needs to be like this:

<button id="add_button" type="button">

otherwise it is a submit button. You click it and the form is submitted.
And because in the <form> you did not specify an action, by default the
action is to load your script again. So your <li> is added (and you see
the flash), then the original script is reloaded and away it goes.
 
E

Evertjan.

RH wrote on 12 jan 2012 in comp.lang.javascript:
I'm a newbie, and just starting to use javascript. I've written a
small program that simply adds an element to an unordered list in the
DOM:

<body>
<form>
<input type="text" name="filePath" size="100" />
<button id="add_button">Add Element</button>
</form>
<ul id="test"></ul>
<script language="JavaScript" type="text/javascript"

Skip the language="JavaScript", that is of last century.
When testing, better use on-page javascript.
The script should be in the said:
src="viewer.js"> </script>
</body>

script in viewer.js:

window.onload = init();

function init() {
var button = document.getElementById("add_button");
button.onclick = create;
}


function create() {
// create the element in the DOM
var listItemViewer = document.getElementById("test");

var test = document.createElement("li");
test.innerHTML = "test list item";
listItemViewer.appendChild(test);

return false; <- this is your error!

without the return false, <form> execution will take place overwriting
the old page.
 
T

Thomas 'PointedEars' Lahn

RH said:
I'm a newbie, and just starting to use javascript.

There is no "javascript". You are using JavaScript, JScript or something
else, depending on the runtime environment (the browser). All of them are
ECMAScript implementations and share most of the syntax elements.
I've written a small program that simply adds an element to an unordered
list in the DOM:

The DOM (Document Object Model) is an API. You are adding an element to the
_document tree_ instead.
<body>
<form>
<input type="text" name="filePath" size="100" />
<button id="add_button">Add Element</button>
</form>
<ul id="test"></ul>
<script language="JavaScript" type="text/javascript" src="viewer.js">
</script>
</body>

script in viewer.js:

window.onload = init();

function init() {
var button = document.getElementById("add_button");
button.onclick = create;
}


function create() {
// create the element in the DOM
var listItemViewer = document.getElementById("test");

var test = document.createElement("li");
test.innerHTML = "test list item";
listItemViewer.appendChild(test);
}

If I run it and click the add button, it flashes the "test list item" on
the screen - if I single step it through the debugger, it shows that it
puts the element in the DOM at the end of the create() function, but then
it gets stripped out? Can anyone help me understand why this is
happening?

Possibility: Because your underlying markup is not Valid [1], there is no
such `ul' element object in the document tree. `ul' elements must have a
child `li' element from the start. You can either provide it with one in
the markup, or create the `ul' element and the `li' element with scripting.

You should also avoid using `innerHTML' for appending plain text. And if
the button should work only with scripting anyway, you can simply use the
corresponding attribute (you should avoid `window.onload' anyway).

Consider this:

viewer.js:

var ul = null;

function create()
{
// create the element in the DOM
if (!ul)
{
ul = document.createElement("ul");
}

if (ul)
{
var li = document.createElement("li");
if (li)
{
li.appendChild(document.createTextNode("test list item"));
ul.appendChild(li);
document.body.appendChild(ul);
}
}
}

In the HTML5 document (it is not Valid HTML4, the `form' element would need
an `action' attribute there):

<body>
<form>
<input type="text" name="filePath" size="100">
<button type="button" onclick="create()">Add Element</button>
</form>
</body>

Please note that the `button' element has compatibility issues (particularly
in IE), so for simple buttons you should use `<input type="button"
value="…">' instead.


HTH

PointedEars
___________
[1] <http://validator.w3.org/>
 
D

Denis McMahon

function create() {
// create the element in the DOM
var listItemViewer = document.getElementById("test");

var test = document.createElement("li"); test.innerHTML = "test list
item";
listItemViewer.appendChild(test);
}

What the others said, but in addition, maybe this is a better create():

function create() {
var listItemViewer = document.getElementById("test");
var test = document.createElement("li");
test.appendChild(document.createTextNode("test list item"));
listItemViewer.appendChild(test);
}

If you're going to use dom functions to create the list element, you
might as well (some might even suggest should) also use the dom functions
to add its content instead of innerHTML.

Otherwise, if you're going to use innerHTML, why not just:

function create() {
var listItemViewer = document.getElementById("test");
listItemViewer.innerHTML = listItemViewer.innerHTML + "<li>test list
item</li>";
}

which is in my opinion a crude, reckless and some might even suggest
bloody stupid way of doing it.

Rgds

Denis McMahon
 
T

Thomas 'PointedEars' Lahn

Denis said:
What the others said, but in addition, maybe this is a better create():

function create() {
var listItemViewer = document.getElementById("test");
var test = document.createElement("li");
test.appendChild(document.createTextNode("test list item"));
listItemViewer.appendChild(test);
}

If you're going to use dom functions to create the list element, you
might as well (some might even suggest should) also use the dom functions
to add its content instead of innerHTML.

It is inefficient to retrieve the element object reference on every click.
So you should cache that somehow. However, if you are using this function
then you must by definition have either an empty `li' element in the
document already (which is not modified by this code, which would be a
rather bad idea) or you must create the `ul' element dynamically, in which
case you have the element object reference already (as I showed).


PointedEars
 
R

R Hall

Thanks - I didn't realize the form tag would cause a button submit by default.
It did the trick.
 
J

John G Harris

There is no "javascript".

One day Thomas will amaze us by suggesting an alternative word or phrase
to replace 'javascript' (all lower case) to describe any or all of these
languages. But if the name is more than 3 words long it's going to be
ignored.

You are using JavaScript, JScript or something
else, depending on the runtime environment (the browser). All of them are
ECMAScript implementations and share most of the syntax elements.

All of them are only partly ECMAScript implementations. Access routes to
the DOM objects, or equivalent, are outside ECMAScript.

The DOM (Document Object Model) is an API. You are adding an element to the
_document tree_ instead.
<snip>

Equally correct is to say he is adding an element to the document.


John
 
G

Gene Wirchenko

Yes, there is. It is the third word in the name of this
newsgroup:
comp.lang.javascript
^^^^^^^^^^
Look! There it is!
One day Thomas will amaze us by suggesting an alternative word or phrase
to replace 'javascript' (all lower case) to describe any or all of these
languages. But if the name is more than 3 words long it's going to be
ignored.

The glass is half-full?

[snip]

Sincerely,

Gene Wirchenko
 
T

Thomas 'PointedEars' Lahn

John said:
One day Thomas will amaze us by suggesting an alternative word or phrase
to replace 'javascript' (all lower case) to describe any or all of these
languages.
BTDT.

But if the name is more than 3 words long it's going to be ignored.

It has two words, three at most.
All of them are only partly ECMAScript implementations. Access routes to
the DOM objects, or equivalent, are outside ECMAScript.

The APIs available for use with a programming language do not change the
nature of that programming language.
<snip>

Equally correct is to say he is adding an element to the document.

No, because the underlying markup does _not_ change.


PointedEars
 
J

John G Harris


Remind us.

I only remember your description of this group's Topic. It was
deficient.


It has two words, three at most.

The APIs available for use with a programming language do not change the
nature of that programming language.

In C++, Java, Pascal and some other languages the standard library is
required for conformance to the language standard.

In JavaScript, JScript, etc the DOM objects are also required, even
though Mozilla, Microsoft, etc wouldn't dream of publishing their
standards.


No, because the underlying markup does _not_ change.

The original document text doesn't change, but the current document
text, rendered from the current parse tree, alias document tree, does.


John
 
T

Thomas 'PointedEars' Lahn

John said:
In JavaScript, JScript, etc the DOM objects are also required, even
though Mozilla, Microsoft, etc wouldn't dream of publishing their
standards.

You have no clue what you are talking about.


PointedEars
 
T

Thomas 'PointedEars' Lahn

John said:
It's looking as though you don't know enough to form a valid opinion on
that.

I do know that it is wrong that "in JavaScript, JScript, etc the DOM objects
are also required", and I know that not only "Mozilla, Microsoft, etc" do
not make their own standards, but that they document their language and DOM
implementations fairly well (up to the point of publishing the source code).
Which is such basic knowledge that your evidently lacking it sufficed for me
to make that assessment (not stating an opinion).


PointedEars
 
D

Denis McMahon

On Sun, 15 Jan 2012 14:19:58 +0000, John G Harris wrote:

[re TPELtroll]
It's looking as though you don't know enough to form a valid opinion on
that.

All he knows how to do is post "You're wrong" or some variation of.

His explanation as to why anything is wrong is invariably "go read the
spec".

He never seems to suggest an alternative that might be "correct".

I gave up reading his posts a long time ago. Even if he knew more than
anyone else on the planet about javascript / html / css / php etc, it
would be impossible to determine determine this from his "contributions"
here, because they seem to consist solely of comments like "that's wrong".

Rgds

Denis McMahon
 
J

John G Harris

I do know that it is wrong that "in JavaScript, JScript, etc the DOM objects
are also required", and I know that not only "Mozilla, Microsoft, etc" do
not make their own standards, but that they document their language and DOM
implementations fairly well (up to the point of publishing the source code).
Which is such basic knowledge that your evidently lacking it sufficed for me
to make that assessment (not stating an opinion).

Microsoft's JScript reference includes the items
comment statement
function statement
this statement
but not
block (not even as compound statement).

I rest my case.

And people who have the delusion that the compiler's source code
specifies a language are mad.

John
 
R

RobG

I'm a newbie, and just starting to use javascript.  I've written a small program that simply adds an element to an unordered list in the DOM: [...]
window.onload = init();

If it is expected that a result of the above is that the init function
will be called when the load event occurs, then that expectation will
not be met.

The call to init will be executed immediatelly and the result
(undefined) assigned to the onload property of the window object. It
"works" in this case only because the script element is placed below
the DOM element it depends upon to sucessfully complete.

Move the script to the head (where scripts are more commonly placed)
and it will fail with an error at the point of attempting to call
button.onclick, since button will be null (as the element with id
"add_button" does not exist in the DOM yet).
 

Ask a Question

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

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top