[英]Remove id div only from first parent
我只想从 div "id = parent" 中删除 div "id = child" 但不删除 "id = parent" 之外的 div "id = child" ??? 当然,在 parent 和外面会有更多具有相同 id 的元素。
<style>
#parent{
width: 150px;
height: 150px;
background-color: blue;
}
#child{
width: 50px;
height: 50px;
background-color: red;
}
</style>
<div id="parent">
<div id="child"></div>
</div>
<div id="child"></div>
<button onclick="myFunction()" >click</button>
<script>
function myFunction(){
document.getElementById("child").remove();
}
</script>
您需要将 html 更改为具有 class 而不是多个元素的 id。
<div id="parent">
<div class="child"></div>
</div>
<div class="child"></div>
<button onclick="myFunction()" >click</button>
然后,使用 javascript 得到 class 的第一个元素,如下所示:
<script>
function myFunction(){
var element = document.getElementsByClassName("child")[0];//the selector will select an
//array of all elements with the same class, so we specify the first by denoting [0]
element.parentNode.removeChild(element);//and then remove that element
}
</script>
编辑:如果你想用一个 id 来做,把代码从
var element = document.getElementsByClassName("child")[0];
至
var element = document.getElementById("child");
如果您不想更改 html,也许您可以通过 parent.childNodes 来完成
function myFunction() {
const parent = document.getElementById("parent");
parent.childNodes.forEach(el => el.id == 'child' && el.remove());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.