Mark wrote:
Hopefully I 'm missing something silly, but I can't find an easy way to loop
Yes!
Seeing as how you've discounted getElementsByTagName('li'), then I guess
we can start at the point where you have a reference to an OL element -
say getElementsByTagName('ol') or getElementById('someOLid').
Now you can just recurse (is there such a word?) down the tree and test
for LI nodes. Some code follows - it's cross browser, it'll work in
Mozilla, Safari and *gasp* IE too - and it will travel down all LIs,
even if you nest several lists (as in the example), but will not escape
the starting node.
The reason your code:
ol.firstChild.firstChild.nodeValue
fails in the zillas is because of the following:
ol.firstChild will grab the first child (a text node) which doesn't have
any children, so there is no ol.firstChild.firstChild and that's where
the script will (likely) end.
Firefox and other similar browsers (including Safari) add text nodes
after just about everything, including UL and OL nodes, so the
firstChild of an OL (or UL for that matter) is a text node type 3 with
zero children. Trying to get the child of a node with no children will
fail.
Did you try using Mozilla's inspector? (Firefox and Safari have
excellent DOM inspectors too).
IE doesn't add the useless text node, so that's likely why your code
works in IE. Without knowing it, your code is IE specific.
The code below travels down every single branch below the start point
and reports only LI nodes (you could add other if you wish). It also
reports the number of iterations required to get where it's up to (i).
To make it more robust, it should test for the text node below the LI to
make sure you get the right one, but I've just used your (somewhat
risky) guess that the first child of the LI is the text node you want.
If you just want the level directly below the starting OL, grab the
firstChild then use nextSibling to travel across the level.
Have fun - Fred.
<html><head><title>list LIs</title>
</head>
<body>
<ol id="anOL">
<li>item 1</li>
<li>item 2</li>
<li>item 3
<ol>
<li>item 3.1</li>
<li>item 3.2</li>
<li>item 3.3
<ol>
<li>item 3.3.1</li>
<li>item 3.3.2</li>
<li>item 3.3.3</li>
</ol>
</li>
<li>item 3.4</li>
</ol>
</li>
<li>item 4</li>
<li>item 5</li>
</ol>
<script type="text/javascript">
var msg = "LI list...";
function listLIs(n,x) {
if (n.nodeName == 'LI') {
msg += '\n LI ' + x + ' : '
+ n.nodeValue + ' : '
+ n.firstChild.nodeValue;
}
for (var i=0; i<n.childNodes.length; i++) {
listLIs(n.childNodes[i],x+'.'+i);
}
}
listLIs(document.getElementById("anOL"),'');
alert(msg);
</script>
</body></html>