I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?
jQuery.contents() can be used with jQuery.filter to find all child text nodes. With a little twist, you can find grandchildren text nodes as well. No recursion required:
$(function() {
var $textNodes = $("#test, #test *").contents().filter(function() {
return this.nodeType === Node.TEXT_NODE;
});
/*
* for testing
*/
$textNodes.each(function() {
console.log(this);
});
});
div { margin-left: 1em; }
child text 1
child text 2
grandchild text 1
grand-grandchild text 1
grandchild text 2
child text 3
child text 4
jsFiddle