Search code examples
jqueryhideelementparentclosest

if div is empty, hide a different div element


I have a blog posts page with "read more/read less" toggle button for each post.

I would like to hide "a.wpex-link" if ".wpex_div p" is empty. The problem is that needs to select its parent/closest link since all posts have the same class.

<a onclick="wpex_toggle(548787318, 'Read more', 'Read less'); return false;" class="wpex-link" href="#" target="_blank">Read less</a>
<div class="wpex_div" id="wpex548787318" style="display: block;">
    <div class="sidebar-content"></div>
    <p></p>
</div>

Solution

  • $('.wpex_div:has(p:empty)').prev('.wpex-link').hide();
    

    $('.wpex_div:has(p:empty)').prev('.wpex-link').hide();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <a onclick="wpex_toggle(548787318, 'Read more', 'Read less'); return false;" class="wpex-link" href="#" target="_blank">Read less</a>
    <div class="wpex_div" id="wpex548787318" style="display: block;">
        <div class="sidebar-content">The p element is empty. That is why the 'Read less' anchor is not displaying</div>
        <p></p>
    </div>