1 回答

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以通過(guò)這種方式檢測(cè)文檔中的評(píng)論(參見(jiàn)代碼片段)?,F(xiàn)在由您來(lái)設(shè)計(jì)一些巧妙的函數(shù)來(lái)刪除注釋之間的元素。. 好的,您要求它,包括一種刪除相等注釋之間元素的方法。
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>
添加回答
舉報(bào)