SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Oct 2005
    Posts
    109
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    getting node text from a ul

    I'm trying to output the text value from a list node. Any idea why it's not working. How do i tell how many childNodes are in the ul element?

    Code:
    function test(){
    
    	var x = document.getElementById("test");
    
    	alert(x.firstChild.nodeValue);
    	
    	
    }
    Code:
    <ul id="test">
      <li>
        Alec
      </li>
      <li>
        Daniel
      </li>
      <li>
        William
      </li>
      <li>
        Stephen
      </li>
    </ul>

  2. #2
    SitePoint Member
    Join Date
    May 2010
    Posts
    17
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah yes, the old "phantom node" talk.

    run a

    Code:
    var nodeArray = x.childNodes;
    Then see what is contained in your nodeArray (you have Firebug right?). If you see something like this:

    Code:
    \n, <li>, \n, <li>, \n
    Then you have pesky phantom nodes. The way around this is to make yourself an array that filters out the phantom nodes. So something like this

    Code:
    var i;
    var liArray = [];
    for (i=0; i < nodeArray.length; i++) {
    if (nodeArray[i].nodeType == 1) { //nodeType == 1 means it's an element node (not a text node like "\n" would be)
    liArray.push(nodeArray[i]);
    }
    }
    then liArray should only contain your <li> elements. Good luck!


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
  •