I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?
I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue
conditional to your filter
function, like a simple $.trim(this.nodevalue) !== ''
:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
});
http://jsfiddle.net/ptp6m97v/
Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen
character, newlines \n
, tabs, etc.), you can try using a Regular Expression. For example, \S
will match any non-whitespace characters:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && /\S/.test(this.nodeValue);
});