i don't understand how DOM counts up divRef.childNodes.length

J

Jake Barnes

This weekend I decided to play around with Javascript a little and try
to teach myself some things about AJAX and DOM. I've been doing
experiments on this page:

http://www.publicdomainsoftware.org/ajaxExperiment.htm

If you go there and click in any box, you'll get some controls. If you
then click "Add an Image" you'll have the chance to add an image. But
how many child elements are there in the box that communicates with
you? I count 4 items at most:

<div id="inputDiv">
<textarea id="inputBox" class="wonderful"></textarea><br />
<input id="submitButton" type="button" value="Submit"
onClick="getInput();">
<input type="button" value="Cancel"
onClick="hideDiv('communicationBox');">
</div>

And yet, in the javascript code, when I try to get the number of child
elements, I get 8 in FireFox and 7 in IE. This is the code that
captures the info and I use alert() to make it visible:

var divRef = document.getElementById("inputDiv");
var firstChildNode = divRef.firstChild;
alert(divRef.childNodes.length);
if (divRef.childNodes.length > 6) {
divRef.removeChild(firstChildNode);
firstChildNode = divRef.firstChild;
}

Why am I getting 7 and 8 instead of 4? I don't get how the DOM is
counted.
 
R

RobG

Jake said:
This weekend I decided to play around with Javascript a little and try
to teach myself some things about AJAX and DOM. I've been doing
experiments on this page:

http://www.publicdomainsoftware.org/ajaxExperiment.htm

If you go there and click in any box, you'll get some controls. If you
then click "Add an Image" you'll have the chance to add an image. But
how many child elements are there in the box that communicates with
you? I count 4 items at most:
[...]

Why am I getting 7 and 8 instead of 4? I don't get how the DOM is
counted.

As Ian said, check the nodes - use the DOM inspector.

Gecko browsers will insert #text nodes to preserve whitespace in the
source document (after collapsing whitespace first).

<table>

<!-- this tr has one child - the td -->
<tr onclick="alert(this.childNodes.length);"><td>Show kids</td></tr>

<!-- this tr has two children - a #text and a td -->
<tr onclick="alert(this.childNodes.length);">
<td>Show kids</td></tr>

<!-- this tr has three children - a #text, td and #text -->
<tr onclick="alert(this.childNodes.length);">
<td>Show kids</td>
</tr>

</table>


But in IE all of them have just one child, the TD.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top