Reputation: 3605
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:
"text" => text
<b>bold</b> => child
"and" => text
<i>italic</i> => child
How to do this in an efficient and elegant way?
Upvotes: 0
Views: 332
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