Fifi
Fifi

Reputation: 3605

Separate text and children in a HTML node in JavaScript

In JavaScript, I would like to split a node to separate text and children. Consider the following node:

<p>text <b>bold</b> and <i>italic</i></p>

I would like to get an array (or something iterable) that looks like:

  1. "text" => text
  2. <b>bold</b> => child
  3. "and" => text
  4. <i>italic</i> => child

How to do this in an efficient and elegant way?

Upvotes: 0

Views: 332

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48683

If you want to get an array of text/HTML for each child node, you can run the children through a switch-statement and check the node type.

Note: Here are all the nodeTypes.

const nodeText = (nodes) => {
  return Array.from(nodes).map(node => {
    switch (node.nodeType) {
      case Node.TEXT_NODE:
        return node.textContent.trim();
      case Node.ELEMENT_NODE:
        return node.outerHTML;
      default:
        return null;
    }
  }).filter(text => text != null);
}

console.log(nodeText(document.querySelector('p').childNodes));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<p>text <b>bold</b> and <i>italic</i></p>

Upvotes: 2

Related Questions