我只想从div“ id = parent”删除div“ id = child”,而不是在“ id = parent”之外删除div“ id = child” ???当然,会有更多具有相同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更改为具有一个类,而不是多个元素的id。
<div id="parent">
<div class="child"></div>
</div>
<div class="child"></div>
<button onclick="myFunction()" >click</button>
然后,使用javascript获取此类的第一个元素:
<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>
如果您不想更改html,也许可以通过parent.childNodes做到这一点
function myFunction() {
const parent = document.getElementById("parent");
parent.childNodes.forEach(el => el.id == 'child' && el.remove());
}