首页 > 解决方案 > 获取两个 HTML 注释中间的内容

问题描述

我需要获取位于两个 HTML 注释中间的 HTML 内容。看代码:

<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->

在这个例子中,我需要得到<p>Hello</p>,我该怎么做?用正则表达式?谢谢阅读。

标签: javascripthtmldom

解决方案


您可以使用 XPath 表达式//comment()来查找注释,循环它们以找到您关心的那些,然后循环从第一个节点开始,直到找到第二个。

const comments = document.evaluate("//comment()", document);
let start;
let end;
while (comment = comments.iterateNext()) {
  if (comment.data.trim() === "Write your comments here") {
    start = comment;
  }
  if (comment.data.trim() === "another comment") {
    end = comment;
  }
}

let current = start.nextSibling;
let matches = [];
while (current !== end) {
  matches.push(current);
  current = current.nextSibling;
}

console.log(matches.map(node => node.textContent));
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->

请注意,如果注释不是兄弟,这将中断,并且我没有进行任何错误处理。


推荐阅读