如果子div为空,则删除父div

时间:2016-08-18 05:40:17

标签: javascript jquery html

我试图删除整个父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()

脚本:(因onload内容呈现而导致冲突)

$('.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>

3 个答案:

答案 0 :(得分: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();
    }
});

答案 1 :(得分:2)

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

答案 2 :(得分: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();
    });
});
相关问题