jQuery: Work with text nodes and comment nodes
Nearly all jQuery traversal functions ignore elements that are not HTML tags.
To work with other type of nodes (like text, comment or CDATA sections) you need to:
- Retrieve child nodes
contents()
(which behaves likechildren()
except that it returns all types of child nodes) - Filter manually using either plain Javascript or jQuery's
filter()
method
Example
Let's write a function that takes a jQuery element and returns an array of all child nodes that are text nodes:
function selectTextNodes($container) {
return $container.contents().filter(function() {
return this.nodeType === 3;
});
}
Also check out this
list of existing node types
Show archive.org snapshot
. 1
is HTML tag, 3
is text, 8
is comment, etc.