如何解决在两个HTML注释中间获取内容
我需要获取位于两个HTML注释中间的HTML内容。查看代码:
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->
在此示例中,我需要获取<p>Hello</p>
,我该怎么做?与正则表达式?
感谢您的阅读。
解决方法
您可以使用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 -->
请注意,如果注释不是兄弟姐妹,这将中断,并且我没有进行任何错误处理。
,您可以使用childNodes并查看Node类型。
function getNodesBetweenComments (wrapper) {
var state = 0;
return Array.from(wrapper.childNodes).filter(node => {
if (node.nodeType === 8) state++;
else return state === 1 && node.nodeType === 1
})
}
const wrapper = document.querySelector("#wrapper");
console.log(getNodesBetweenComments(wrapper));
const wrapper2 = document.querySelector("#wrapper2");
console.log(getNodesBetweenComments(wrapper2));
<div id="wrapper">
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<!-- another comment -->
</div>
<div id="wrapper2">
<p>hello</p>
<!-- Write your comments here -->
<p>hello</p>
<p>there</p>
<p>world</p>
<!-- another comment -->
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。