2016-08-18 81 views
0

我試圖刪除整個父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> 

回答

2

循環訪問'.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(); } });' –

1

試試這個。如果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

2

純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>