0

Is there a way to allow me to iterate through an ordered list similar in functionality as table.rows? I am using Javascript.

The reason I ask this is because I have an ordered list that contains another ordered list inside. I just want to return the parent list items and not the child.

<ol id="pList">
    <li>Item A</li>
    <li>
        <ol id="cList">
            <li>A's Child 1</li>
            <li>A's Child 2</li>
        </ol>
    </li>
    <li>Item B</li>
    <li>Item C</li>
    <li>Item D</li>
</ol>

I now use getElementsbyTag and that returns all li's including the one in cList. I just want the ones in pList.

Thanks

FYI: I would prefer it done in Javascript. The code has to work within Greasemonkey. I don't really know much about jquery and I am not really much of a javascript programmer.

C3PO
  • 114
  • 1
  • 10

3 Answers3

5

There is no specific property that gives you direct access to the <li> children of an <ol>.

However it is very easy to enumerate them, particularly when you consider that the only legal children of an <ol> must be white space text nodes and <li> nodes.

var ol = document.getElementById('pList');
var li = [];
var node = ol.firstChild;
while (node) {
    if (node.tagType === 3 && node.tagName === 'LI') {
        li.push(node);
    }
    node = node.nextSibling;
}

At the end of which, the array li contains the required children.

The above code will work in any browser. The .children collection has problems on older versions of MSIE, and querySelectorAll is even more modern (and therefore less widely supported).

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

If using querySelectorAll()* is an option for you, it's easy:

var listItems = document.querySelectorAll( '#pList > li' );

* note: it's a native DOM method, and has nothing to do with jQuery

Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
0

There's a table of immediate children in every javascript object :

document.getElementById('pList').children

You can even iterate through it and check whatever your need :

var el = document.getElementById('pList');
for (var i = 0; i < el.children.length; i++) {
    if (el.children[i].tagName == "LI") {
        el.children[i].doWhatever();
    }
}
Florian F.
  • 4,700
  • 26
  • 50
  • 2
    See http://stackoverflow.com/questions/7935689/what-is-the-difference-between-children-and-childnodes-in-javascript – Alnitak Feb 14 '13 at 15:36
  • I was hoping there was direct access like table.rows. So I guess old fashioned way will do. – C3PO Feb 14 '13 at 15:48