I’m primarily a C#, Java, PHP Developer; associated databases encapsulated. Seemingly irrelevant, but a valid precursor to the statement that I feel like I’m 15 again; glaring at this… disappointingly simple javascript, that doesn’t seem to be turning up anything for me.
My intention here is to loop through the nodes in my current document, evaluate their attributes, and perform actions on particular nodes. My code is as follows ( again… so simple I feel like a dunce ), but the output is rather inconsistent.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function TraverseDocument()
{
var Root = document.documentElement;
for( Element in Root.childNodes )
{
document.writeln(Element);
}
}
</script>
</head>
<body onLoad="javascript: TraverseDocument();">
<div id="test" testAttr="testData">
</div>
</body>
</html>
Now; consider that this is just my fifth pass at this ( tutorials, examples, etc ), and I’ve tried a few permutations on this code:
// document.writeln(Element.nodeType);
// document.writeln(Element.nodeName);
// document.writeln(Element.nodeValue);
All of which come up short; displaying ‘undefined’. The current code ( as shown in my first code block ) outputs the following:
0 1 2 length item
Can anyone point me at where I’m going wrong here? Rookie question; but one that I still can’t manage to put my finger on. Thanks ahead of time.
Simple enough, the for loop you’ve written iterates the properties of the object, rather than the items in the array, what you probably want is actually: