Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery InnerText not including sub element

Im wondering how I would get the text of a nested list item without getting the text of its children i.e.

<ul>
   <li id="node">
      I want this
    <ul>
       <li>
          I dont want this
        </li>
    </ul>
    </li>
</ul>

Now using jquery with $('#node').text() gets me all text, where as I just want the "I want this" string.

Any help appreciated.

Cheers, Chris.

like image 697
Owen Avatar asked Sep 25 '09 11:09

Owen


2 Answers

Tim's solution will work. If your markup is always fixed in that format and you only need to read that first stretch of text up to the child element, you could even get away with simply:

node.firstChild.data
like image 69
bobince Avatar answered Oct 06 '22 13:10

bobince


The following will get you a concatenated string of all the text nodes that are direct children of a node:

function getChildText(node) {
  var text = "";
  for (var child = node.firstChild; !!child; child = child.nextSibling) {
    if (child.nodeType === 3) {
      text += child.nodeValue;
    }
  }
  return text;
}

alert( getChildText(document.getElementById("node")) );
like image 37
Tim Down Avatar answered Oct 06 '22 14:10

Tim Down