Helpful Information
 
 
Category: DOM and JSON scripting
TreeWalker Problems

Right now I'm just getting used to the properties/methods of the TreeWalker object (my curiosity is due to jkd's many posts on the subject). Although, I'm having a problem: I can't read any other nodes besides the root. For instance, I've got a HTML structure like so:


<html>
<head>
<title>DOM TreeWalker</title>
<script type="text/javascript">
function walkTree() {
var tw=document.createTreeWalker(document.body,1,null,true);
var body=tw.currentNode;
var p=body.firstChild;

body.addEventListener("click",new Function("alert('event fired');"),false);
alert(p.innerHTML);
}
</script>
</head>
<body onload="walkTree();">
<p id="myParagraph">my paragraph</p>
</body>
</html>

When I add the event listener it works, but when I try to alert the innerHTML of the firstChild node (which is stored in the variable "p") it alerts the value "undefined".

I'm not sure of the problem so I was hoping someone else could help me solve this problem.

Happy coding! :)

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Treewalker</title>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1;" />
<script type="text/javascript">
function walkTree()
{
var tw = document.createTreeWalker(document.body,1,null,true);
var body = tw.currentNode;
var p = body.firstChild;

body.addEventListener("click",new Function("alert('event fired');"),false);
alert(p.nextSibling.innerHTML);
}
</script>
</head>
<body onload="walkTree();">
<p id="myParagraph">my paragraph</p>
</body>
</html>

Maybe Jason can explain this better, because I'm confused :eek:

p = [object Text]
p.nextSibling = [object HTMLParagraphElement]

Thank you - that worked well.
-------------------------------------

Sorry about the misplaced post, mods. I just wasn't thinking.

Happy coding! :)

The reason you were getting undefined for the p element is that Mozilla interprets text-indents as TextNode's in the DOM. IE doesn't.

which means:


<body>
XXXX<div>bla</div>
</body>


I used XXXX to represent the whitespace.

body.firstChild is that string of X's, parsed as a TextNode with nodeValue == '&nbsp;&nbsp;&nbsp;&nbsp;';

Make sense? :)

Anyway, for a working example of TreeWalker, check out the Post a Javascript forum where you'll see something I just posted. :)










privacy (GDPR)