How do I hide a parent div if the child div doesn't contain an tag?

后端 未结 4 1672
梦毁少年i
梦毁少年i 2021-01-27 07:41

I\'m trying to hide a parent div (i.e., #post) if the child div (i.e., .post-title) doesn\'t contain an tag. Any insight in how to accomplish this correct

相关标签:
4条回答
  • 2021-01-27 08:17

    You can simply use jQuery's .filter

    Like so:

    $('.post-title').filter(function(i) { return !$(this).find('a').length }).hide();
    

    See example below

    $('.post-title').filter(function(i) { return !$(this).find('a').length }).hide();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id="latest">
        <div id="post">
            <div class="post-image post-image-1"></div>
            <div id="post-content">
                <div class="post-title post-title-1"><a href="javascript:void">Link here</a></div>
                <div id="post-date"></div>
            </div>
        </div>
    <div id="post">
            <div class="post-image post-image-2"></div>
            <div id="post-content">
                <div class="post-title post-title-2">NO LINK</div>
                <div id="post-date"></div>
            </div>
        </div>
    </div>
    <div id="latest">
        <div id="post">
            <div class="post-image post-image-1"></div>
            <div id="post-content">
                <div class="post-title post-title-1">NO LINK</div>
                <div id="post-date"></div>
            </div>
        </div>
    <div id="post">
            <div class="post-image post-image-2"></div>
            <div id="post-content">
                <div class="post-title post-title-2"><a href="javascript:void">Link here</a></div>
                <div id="post-date"></div>
            </div>
        </div>
    </div>

    0 讨论(0)
  • 2021-01-27 08:30

    Firstly: dont use IDs mulitple times. Every ID should be unique :)

    Secondly: $('.post').not( ':has(".post-title a")' ).addClass('hide')

    0 讨论(0)
  • 2021-01-27 08:34

    Note: It's a crime to duplicate the ids.

    0 讨论(0)
  • 2021-01-27 08:36

    Just use jQuery's toggle using a boolean from checking the length of the children:

    /* Loop Through Parents */
    $('#post').each(function() {
        $(this).toggle($(this).children('a').length > 0);
    });
    
    0 讨论(0)
提交回复
热议问题