如何在 Javascript 中删除父节点中重复的 childNode 元素?

如何从父元素中删除任何重复的子节点,以便父元素中具有相同 innerText 的元素不超过 1 个?下面的 HTML 示例说明之前和之后的内容。


HTML


<div id="parent">

    <div class="child">hello</div>

    <div class="child">hello</div>

    <div class="child">world</div>

    <div class="child">world</div>

</div>

目标


<div id="parent">

    <div class="child">hello</div>

    <div class="child">world</div>

</div>


郎朗坤
浏览 135回答 2
2回答

梦里花落0921

尝试这个。var children = document.querySelectorAll(".child")var tmpTexts = []for (const c of children) {&nbsp; &nbsp; if (tmpTexts.includes(c.innerText)) continue&nbsp; &nbsp; tmpTexts.push(c.innerText)&nbsp; &nbsp; c.parentNode.removeChild(c)}<div id="parent">&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">hello</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">hello</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">world</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">world</div></div>

宝慕林4294392

这是另一种方法:const children = document.querySelectorAll('.child');function filterChildren(text, i, textArray) {&nbsp; if ( textArray.indexOf(text) <= textArray.lastIndexOf(text) && textArray.indexOf(text) !== i ) {&nbsp; &nbsp; children[i].parentNode.removeChild( children[i] )&nbsp; }}Array&nbsp; .from(children)&nbsp; .map( child => child.innerHTML )&nbsp; .forEach(filterChildren);<div id="parent">&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">hello</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">hello</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">world</div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="child">world</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript