[英]Remove the parent div if child div is empty
我正在嘗試刪除整個父div,如果它沒有wc-gallery
類。 我在腳本中所擁有的與我所需要的相反。 基本上,它隱藏了所有帶有wc-gallery
的東西。
腳本:
// 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()
。
腳本:(由於加載內容呈現而引起的沖突)
$('.gallery-container2').hide();
$(function(){
$(".gallery-item").each(function(){
$(this).children('.wc-gallery').parents('.gallery-container2').show();
});
});
HTML :(第一組是應該可見的第二組是需要刪除或隱藏的組。)
<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();
}
});
用ES6術語,您可能會喜歡純JS。
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>
嘗試這個。 如果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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.