472,796 Members | 1,088 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,796 software developers and data experts.

looping through <li>'s

Hopefully I 'm missing something silly, but I can't find an easy way to loop
all list items in a simple <ol>. I was hoping a for loop as shown below
would be enough, however clicking "alert all" in the following example gives
me all but the first <li> element. The alertfirst() function finds the first
<li> with no problem. There are multiple lists on the page, so
getElementsByTagName('li') is probably not the most elegant solution. Btw.
my Mozilla crashed when I tried this code, but this is for IE only.

<script type="text/javascript">
function alertfirst() {
var ol=document.getElementsByTagName('ol')[0];
alert( ol.firstChild.firstChild.nodeValue );
}
function alertall() {
var ol=document.getElementsByTagName('ol')[0];
for( var i=ol.firstChild; i=i.nextSibling; i!==null) {
alert( i.firstChild.nodeValue );
}
}
</script>
<ol>
<li>first</li>
<li>second</li>
<li>third</li>
</ol>
<a href="" onclick="alertfirst();return false">alert first</a>
<a href="" onclick="alertall();return false">alert all</a>

Thanks ia,
Mark
Jul 23 '05 #1
4 4416


Mark wrote:

var ol=document.getElementsByTagName('ol')[0];


You can and probably want to call getElementsByTagName on the ol element:
var listItems = ol.getElementsByTagName('li');
for (var i = 0; i < listItems.length; i++) {
...
}
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #2
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>
Jul 23 '05 #3
I know I am late, but I can't let such nonsense go uncommented.

Fred Oz wrote:
[...]
Firefox and other similar browsers (including Safari) add text nodes
after just about everything, [...]
They don't.
IE doesn't add the useless text node, [...]


The text nodes are already there in the parse tree, as you can observe using
the W3C HTML Validator, for example. They have been created by indentation
and linebreaks in the source code. What IE 5+ really does is to disregard
the DOM Level 1+ HTML Specification in this regard although implementing
many of its methods and properties, removing some text nodes (usually those
after the start tag of block elements) from the parse tree or at least hide
them from DOM access while inconsistently preserve others (usually those
before the close tag of elements).

"Empty" text nodes (they are not really empty, but contain whitespace
characters) are not useless, they can be used to insert new text without
inserting a new element. *This* is how a shoe is done. [psf 4.6]
PointedEars
--
Error: Out of cheese, restock hamster wheel
Jul 23 '05 #4
Thomas 'PointedEars' Lahn wrote:
I know I am late, but I can't let such nonsense go uncommented.


The 'late' part is somewhat understated! :-)

The comment was somewhat flippant and the result of observing the
behaviour of various browsers without specific reference to the spec.

Thank you for the clarification - I can cop enlightenment quite
happily.

--
Fred
Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Kelvin | last post by:
Basically, my texts consists of normal text stream and some quotations. This is my text stream, and inside "this streams" there are some "quotation pairs" which are to be replaced like this:...
8
by: Michael | last post by:
This is a two-part question to which I haven't been able to find an answer anywhere else. 1. Is it possible to format the bullet/number character of the <li>? In my styles sheet, I have the <li>...
1
by: Randall Sell | last post by:
OK, I am utterly stumped. The code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <style type="text/css"> ul {...
4
by: Matt | last post by:
Hi, Got an unordered list with 100% width, with 5 list items of 20% width styled to fill the width of the container element. Renders fine in Mozilla, but when you change the size of the window...
4
by: abs | last post by:
Anybody has an idea how to get the <ul> element which is not nested in <li> element ? In other words I have several lists like this: <ul id="1"> <li>Aaaaaaaa</li> <li>Bbbbbbbb</li>...
2
by: Shaun | last post by:
Hello! I have a quick question regarding CSS and having it applied to all elements. I am trying to eliminate the gap between a paragraph and a list that usually occurs in html and I've found...
2
by: Andrew Donaldson | last post by:
I'd welcome some help in understanding what's going on with graphical browsers in the navigation list at: http://www.bounceandtickle.org.uk/index.html (This site is not about what it might...
5
by: Syl | last post by:
Hello experts!! The top menu navigation bar displays perfectly in IE, but does not display properly in Mozilla or Netscape : http://checkeredshirt.com/textonly.html For some reason the non-IE...
9
by: eros | last post by:
<li>List <ul> <li>List1</li> <li>List2</li> <li>List3</li> </ul> </li> How to call the php code from that html tags... when I click List1?
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.