jQuery.contents()
можно использовать с jQuery.filter
, чтобы найти все дочерние текстовые узлы. С небольшим завихрением вы также можете найти текстовые узлы внуков. Не требуется рекурсия:
$(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