如果它有一个具有特定类名的子div,则需要从DOM中删除一个div,而不删除该子div。
我尝试在if / then语句中使用.remove(),但是当我这样做时,它仍然会删除目标父div的所有实例,即使那些没有子实例的实例。
B类父级和子类会自动生成。
<div class="overall">
<div class="parent">
<div class="child-type-A">
// stuff that can't be deleted
</div>
</div>
<div class="parent">
<div class="child-type-B">
// more stuff
</div>
</div>
<div class="parent">
<div class="child-type-B">
// even more stuff
</div>
</div>
</div>
如果孩子的子类为child-type-A,我想删除整个父div,如下所示:
<div class="overall">
<div class="child-type-A">
// stuff that can't be deleted
</div>
<div class="parent">
<div class="child-type-B">
// more stuff that can't be deleted
</div>
</div>
<div class="parent">
<div class="child-type-B">
// even more stuff that can't be deleted
</div>
</div>
</div>
这是我认为可以使用的jQuery,但不起作用(如果存在child-type-A,它将删除所有父母和孩子)。
if( '.parent > .child-type-A' ) {
$( 'parent' ).remove();
}
我希望以“ if”为目标的div是唯一受影响的div,有没有办法做到这一点?
答案 0 :(得分:0)
您需要这样做:-
$(document).ready(function(){
$( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
//you can do this one also
//$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});
工作片段:-
$(document).ready(function(){
$( '.child-type-A' ).closest('.parent').replaceWith($( '.child-type-A' ).closest('.parent').contents());
//you can do this one also
//$( '.child-type-A' ).parent('.parent').replaceWith($( '.child-type-A' ).parent('.parent').contents());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
<div class="parent">
<div class="child-type-A">
// stuff that can't be deleted
</div>
</div>
<div class="parent">
<div class="child-type-B">
// more stuff
</div>
</div>
<div class="parent">
<div class="child-type-B">
// even more stuff
</div>
</div>
</div>
如果child-type-A
div中存在多个overall
div:-
$(document).ready(function(){
$('.parent').each(function(){
if($(this).children('div').hasClass('child-type-A')){
$(this).replaceWith($(this).contents());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="overall">
<div class="parent">
<div class="child-type-A">
// stuff that can't be deleted
</div>
</div>
<div class="parent">
<div class="child-type-B">
// more stuff
</div>
</div>
<div class="parent">
<div class="child-type-B">
// even more stuff
</div>
</div>
<div class="parent">
<div class="child-type-A">
// some other stuff
</div>
</div>
</div>