jQuery: Work with text nodes and comment nodes

Posted Over 9 years ago. Visible to the public.

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 like children() 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.

Henning Koch
Last edit
7 months ago
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2014-08-18 06:57)