1 回答
TA贡献1875条经验 获得超5个赞
您可以通过这种方式检测文档中的评论(参见代码片段)。现在由您来设计一些巧妙的函数来删除注释之间的元素。. 好的,您要求它,包括一种删除相等注释之间元素的方法。
const root = document.querySelector("body");
const allEls = [...root.childNodes];
const IS_COMMENT = 8;
allEls.forEach((el, i) => {
if (el.nodeType === IS_COMMENT) {
// we have a comment. Find the (index of) next equal comment in [allEls]
// from this point on
const subset = allEls.slice(i + 1);
const hasEqualNextComment = subset
.findIndex(elss =>
elss.nodeType === IS_COMMENT &&
elss.textContent.trim() === el.textContent.trim());
// if an equal comment has been found, remove every element between
// the two comment elements
if (hasEqualNextComment > -1) {
subset.slice(1, hasEqualNextComment - 1)
.forEach(elss =>
elss.parentNode && elss.parentNode.removeChild(elss));
}
}
});
body {
font: normal 12px/15px verdana, arial;
margin: 2rem;
}
<!-- WP QUADS Content Ad Plugin v. 2.0.17 -->
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
<!-- WP QUADS Content Ad Plugin v. 2.0.17 -->
<!-- other comment -->
<ul>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
</ul>
<!-- other comment: the above is kept -->
<!-- something 2 remove -->
<div>item 7</div>
<!--something 2 remove-->
<div>item 8</div>
<p>
<b>The result should show item 4 - item 6, item 8 and the
text within this paragraph</b>.
<br><i>Note</i>: this will only work for top level comments
within the given [root] (so, not for comments that nested
within elements).
<br>Also you may have to clean multiline-comments
from line endings for comparison.
</p>
添加回答
举报