SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    Uruguay
    Posts
    74
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to count LI elements from a list

    Hi, I have the next list:


    HTML Code:
    <ul id='myul'>
     <li>a</li>
     <li>b
      <ul>
       <li>b1</li>
       <li>b2</li>
       <li>b3</li>
      </ul>
     </li>
     <li>c</li>
     <li>d</li>
    </ul>

    I would like to know how can I count the LI elements from 'myul' ( just a,b,c,d )

    But not count b1, b2 and b3, in this case the function should return 4

    Thanks

  2. #2
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code JavaScript:
    var ul = document.getElementById("myul");
    var liNodes = [];
     
    for (var i = 0; i < ul.childNodes.length; i++) {
    	if (ul.childNodes[i].nodeName == "LI") {
    		liNodes.push(ul.childNodes[i]);
    	}
    }

    liNodes will contain the LI nodes.

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    Uruguay
    Posts
    74
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you!

  4. #4
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Firefox, Safari and Opera supports document.evaluate which makes life easier since you can use XPath to get the nodes you want:
    Code JavaScript:
    var ul = document.getElementById("myul");
    var result = document.evaluate("li", ul, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
     
    var nextLi;
     
    while (nextLi = result.iterateNext()) {
    	alert(nextLi.firstChild.data);
    }
    More elegant and powerful solution than above, but it does not work in IE...


  5. #5
    SitePoint Wizard
    Join Date
    Nov 2004
    Location
    Nelson BC
    Posts
    2,310
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The IE way:
    Code:
    var myUL = document.getElementById("myUL");
    var list = myUL.children.tags("LI");
    alert(list.length);


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •