Javascript 仅从第一个父级中删除id div
我只想从div id=parent中删除div id=child,但不想删除id=parent之外的div id=child??? 当然,在父元素内部和外部将有更多具有相同id的元素Javascript 仅从第一个父级中删除id div,javascript,function,parent-child,removechild,Javascript,Function,Parent Child,Removechild,我只想从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-col
<style>
#parent{
width: 150px;
height: 150px;
background-color: blue;
}
#child{
width: 50px;
height: 50px;
background-color: red;
}
</style>
您需要更改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元素=document.getElementsByClassNamechild[0]
到
var element=document.getElementByIdchild 如果不想更改html,也许可以通过parent.childNodes执行此操作
function myFunction() {
const parent = document.getElementById("parent");
parent.childNodes.forEach(el => el.id == 'child' && el.remove());
}
你不应该有两个元素具有相同的id,使用类如何?不能有多个元素具有相同的id。使用某个类,你可以通过查询选择器选择该类的第一个元素。我知道这可以通过类完成,但我需要一个id,一些想法?如果你需要id,你可以在我的答案中使用id,但再次,不能有多个元素具有相同的id。如果有,则DOM将只识别DOM中第一个元素的id。具有相同id的第二个元素将被视为没有id。
<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>
function myFunction() {
const parent = document.getElementById("parent");
parent.childNodes.forEach(el => el.id == 'child' && el.remove());
}