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
2008-11-18 13:47:45
actually $(elem) .contents() .filter(function() { return this.nodeType == Node.TEXT_NODE; });is enough
Jauco
2009-07-11 13:53:14
Does not work under IE7. Node is undefined.
rafek
2009-12-29 08:09:39
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
2009-12-29 20:00:54
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
2010-10-15 14:12:28
+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
2010-02-02 09:08:49
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
2010-10-07 06:06:05