用JavaScript在HTML节点中分离文本和子节点



在JavaScript中,我想拆分一个节点来分隔文本和子节点。考虑以下节点:

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

我想得到一个数组(或可迭代的东西(,看起来像:

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

如何以高效优雅的方式做到这一点?

如果您想为每个子节点获取一个text/HTML数组,可以通过switch语句运行子节点并检查节点类型。

注意: 以下是所有节点类型

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>

最新更新