Read more

jQuery: Work with text nodes and comment nodes

Henning Koch
August 18, 2014Software engineer at makandra GmbH

Nearly all jQuery traversal functions ignore elements that are not HTML tags.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2014-08-18 08:57)