我只想从div"id=parent"中删除div"id=child",但不想在"id=paren"之外删除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>
编辑:如果你想用一个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());
}