views:

8099

answers:

3

I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

+15  A: 

Jauco posted a good solution in a comment, so I'm copying it here:

$(elem)
  .contents()
  .filter(function() {
    return this.nodeType == Node.TEXT_NODE;
  });
Christian Oudard
actually $(elem) .contents() .filter(function() { return this.nodeType == Node.TEXT_NODE; });is enough
Jauco
Does not work under IE7. Node is undefined.
rafek
IE7 doesn't define the Node global, so you have to use this.nodeType == 3, unfortunately: http://stackoverflow.com/questions/1423599/node-textnode-and-ie7
Christian Oudard
Does this not only return the text nodes that are the direct children of the element rather than descendants of the element as the OP requested?
Tim Down
+1  A: 

I know this thread's a bit old, but here's a handy script turning this into a jquery function. http://refactormycode.com/codes/341-jquery-all-descendent-text-nodes-within-a-node#refactor_12159

murraybiscuit
A: 
<input type="checkbox" id="1">Title 1
<input type="checkbox" id="2">Title 2

<script>
alert($('#1')[0].nextSibling.nodeValue;//Title 1
</script>
diyism