Please help me understand this DOM thing

R

RC

I want to recursively go through to an element node.

Here are the simple lines

<a href="#" onClick="startANode('ul1')">Recursive Read</a>

<ul id="ul1">
<li>line 1<b>bold 1<i>italic 1<u>under 1</u></i></b></li>
<li><b><i><u>line 2</u></i></b></li>
<li><b><i><u>line 3</u></i></b></li>
<li><b><i><u>line 4</u></i></b></li>
<li><b><i><u>line 5</u></i></b></li>
</ul>


But my java script only goes through the line 1. It never
goes through line 2 to line 5. Can you help me find the problem
in my script?

Thank Q in advance!

BTW, why DOM has firstChild, lastChild but doesn't have nextChild?

Here is the java script

<script type="text/javascript">

function startANode(id) {
var thisNode = document.getElementById(id);
recursiveRead(thisNode);
}
function recursiveRead(node) {
//alert(id);
if (! node.hasChildNodes()) {
alert(
"Node name = " + node.nodeName + "\n" +
"Node value = " + node.nodeValue + "\n" +
"Node type = " + node.nodeType + "\n" +
"Node id = " + node.id + "\n" +
"Node data = " + node.data + "\n"
);
} else {
nodeList = node.childNodes;
alert(nodeList.length);
for (var i = 0; i < nodeList.length; i++) {
aNode = nodeList;
recursiveRead(aNode);
}
}
}
</script>
 
M

Martin Honnen

RC said:
BTW, why DOM has firstChild, lastChild but doesn't have nextChild?

It has nextSibling and previousSibling so you could access the first
child with var child = node.firstChild, then the next child with
child.nextSibling. And you can loop through the childNodes collection.

function recursiveRead(node) {
//alert(id);
if (! node.hasChildNodes()) {
alert(
"Node name = " + node.nodeName + "\n" +
"Node value = " + node.nodeValue + "\n" +
"Node type = " + node.nodeType + "\n" +
"Node id = " + node.id + "\n" +
"Node data = " + node.data + "\n"
);
} else {
nodeList = node.childNodes;
alert(nodeList.length);
for (var i = 0; i < nodeList.length; i++) {
aNode = nodeList;
recursiveRead(aNode);


It is generally a good idea to declare variables and use local
variables, it becomes mandatory once you want to write recursive
functions so use

else {
var nodeList = node.childNodes;
alert(nodeList.length);
for (var i = 0; i < nodeList.length; i++) {
var aNode = nodeList;
recursiveRead(aNode);
}

and your function should do what you want.
 
R

RC

Martin said:
It is generally a good idea to declare variables and use local
variables, it becomes mandatory once you want to write recursive
functions so use


Thank Q very very much Martin! Local variable, local variables.
I remember that in future.
 

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,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top