删除父div如果子div为空

问题描述:

我试图删除整个父div如果它没有wc-gallery类。我在剧本中的内容与我需要的相反。基本上它隐藏了所有有wc-gallery的东西。删除父div如果子div为空

SCRIPT:

// Additional Scripts 
$(window).load(function() { 
    $(".gallery-container2 .gallery-item .wc-gallery").hide(); 
}); 
$(".gallery-container2 p").click(function() { 
    var id = $(this).data('id'); 
    $("[data-id=" + id + "].gallery-item .wc-gallery").toggle() 
}); 


$(function(){ 
    $(".gallery-item").each(function(){ 
     $(this).children('.wc-gallery').parents('.gallery-container2').hide(); 
    }); 
}); 

基本上,这将正常工作,如果我隐藏所有的容器和事后显示子DIV虽然我的内容不会因脚本冲突呈现。解决这个没有冲突的唯一方法是先装载所有的容器,然后装入hide()remove()它们。

SCRIPT:(冲突因为onload内容渲染)

$('.gallery-container2').hide(); 
$(function(){ 
    $(".gallery-item").each(function(){ 
     $(this).children('.wc-gallery').parents('.gallery-container2').show(); 
    }); 
}); 

HTML:(1集是一个应该是可见的第二组需要被删除或隐藏的一个)

<ul> 
    <li><div class="gallery-container2"> 
     <p data-id="1723"><strong>some text</strong></p> 
     <div class="gallery-item" data-id="1723"> 
      <div class="wc-gallery" style="display: none;"></div> 
     </div> 
    </div></li> 
    <li><div class="gallery-container2"> 
     <p data-id="2455"><strong>View before and after</strong></p> 
     <strong></strong> 
     <div class="gallery-item" data-id="2455"> 
      <div><div></div></div> 
     </div> 
    </div></li> 
</ul> 

循环访问'.gallery-container2'元素,找出它是否有'.wc-gallery'子元素。如果不隐藏该元素。

$('.gallery-container2').each(function(){ 
    var $this = $(this); 

    //find element with 'wc-gallery' class 
    var hasGallery = $this.find('.wc-gallery').length > 0; 

    if(!hasGallery){ 
     $this.hide(); 
    } 
}); 
+0

感谢您的使用。 – MIke

+0

如果你想压缩它 '$('。gallery-container2')。each(function(){if(this).find('.wc-gallery')。length === 0) { $(this).hide(); } });' –

试试这个。如果div的子类.wc-gallery比它会显示父母,否则隐藏父母。

$(function() { 
    $(".gallery-item").each(function() { 
    if($(this).children('.wc-gallery').length > 0) 
     $(this).parents('.gallery-container2').show(); 
    else 
     $(this).parents('.gallery-container2').hide(); 
    }); 
}); 
+0

编辑的HTML。 'wc-gallery'在'hide()'onload – MIke

+0

如果'.wc-gallery'在那里,它不会显示div。 – Mairaj

+0

@MichaelPon jsut给这个答案一个尝试。 – Mairaj

纯JS你可能会这样做在ES6条款。

var divsToHide = document.querySelectorAll("div div :not(.wc-gallery)"); 
 
for (var div of divsToHide) div.parentElement.parentElement.style.display = "none";
<div class="gallery-container2"> 
 
    <p data-id="1723"><strong>some text</strong> 
 
    </p> 
 
    <div class="gallery-item" data-id="1723"> 
 
    <div class="wc-gallery">first container</div> 
 
    </div> 
 
</div> 
 

 
<div class="gallery-container2"> 
 
    <p data-id="1724"><strong>some text</strong> 
 
    </p> 
 
    <div class="gallery-item" data-id="1724"> 
 
    <div> 
 
     <div>second container</div> 
 
    </div> 
 
    </div> 
 
</div>