简体   繁体   English

在原始JavaScript中删除带有特定子级(嵌套至少2个级别)的所有元素

[英]Remove all elements with a certain child (nested at least 2 levels in), in vanilla JavaScript

Say I have 2 HTML objects. 说我有2个HTML对象。

The first is 1 div object: 第一个是1 div对象:

<div class="d1">
</div>

The second is a 3 div object with respective nesting: 第二个是具有相应嵌套的3 div对象:

<div class="d1">
    <div class="d2">
        <div class="d3">
        </div>
    </div>
</div>

As you can see, the third is the deepest. 如您所见,第三个是最深的。

Let's also assume I have a webpage with 50 elements of the first object, and 50 elements of the second object. 还假设我有一个网页,其中第一个对象包含50个元素,第二个对象包含50个元素。

How could I delete all HTML objects containing a certain element nested deep inside them (in this case, the element with .d3 ). 我如何删除所有包含嵌套在其中的特定元素的HTML对象(在本例中为.d3元素)。

I could do: 我可以做:

let f = document.querySelector('.d1');
let s = document.querySelector('.d2');
let t = document.querySelector('.d3');

if (t.parentNode == s && s.parentNode == f) {
    f.remove();
}

In jQuery I could also do: 在jQuery中,我也可以这样做:

if( $(f)[1].hasChildNodes() ) {
    f.remove();
}

What is an efficient way to do that in vanilla JS? 在香草JS中,有效的方法是什么?

Update: 更新:

I used a 3 level object just for the sake of a simple example. 出于简单的示例,我使用了3级对象。 Please assume there might be much more children we could target, say, the 300th child. 请假设可能有更多的孩子可以作为我们的目标,例如第300个孩子。 For example, if the object includes child 30, or 300 (instead of 3), remove the object. 例如,如果对象包括子级30或300(而不是3),则删除该对象。 One answer suggests adding an id for the relevant child (say, child number 55). 一个答案建议为相关孩子添加一个id (例如,孩子编号55)。 I think this is a good approach to cover the larger collections. 我认为这是覆盖较大系列的一个好方法。

You can select such nested elements using ".d1 > .d2 > .d3" selector, and then remove them using removeChild or remove function. 您可以使用".d1 > .d2 > .d3"选择器选择此类嵌套元素,然后使用removeChildremove函数将其remove

 var d3Elements = document.querySelectorAll(".d1 > .d2 > .d3"); for(var i = 0; i < d3Elements.length; i++) { console.log(d3Elements[i]); d3Elements[i].parentElement.removeChild(d3Elements[i]); } 
 <div class="d1"> D1 </div> <div class="d1"> D1 <div class="d2"> D2 <div class="d3"> D3 </div> </div> </div> 

Set an id for the div for which you want to remove all children: 为您要删除其所有子级的div设置一个ID:

<div class="d1">
    <div id="removchildren" class="d2">
        <div class="d3">
        </div>
    </div>
</div>

Get that element and remove inner html 获取该元素并删除内部html

var myDiv = document.getElementById("removchildren");
myDiv.innerHTML = '';

You can also traverse and make it dynamic using myDiv.childNodes 您还可以使用myDiv.childNodes遍历并使其动态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM