Search code examples
jquerydomdom-traversaljquery-traversing

Jquery Traverse DOM


I have the following code:

<p class="represent">Representing</p>
<div class="clients_wrap">
    <ul class="clients">
        <li><img src="{{ client.get_sized_image }}"></li>
    </ul>
</div>

This chunk is repeated a number of times. The number of list items may vary between 0 and 10+, but if it is 0 then I need to hide the p.represent tag that precedes it – this needs to be independant for each repeated code block.

I've tried a number of things but can't quite figure it out e.g.

function hideEmptyClients() {
    if ( $('ul.clients li').length >= 1 ) {
        $('ul.clients').parent().closest('p').hide();
    }
}
$(function() {
    hideEmptyClients();
});

SOLVED: Best solution provided by Tomalak:

$(function () {
    $('ul.clients:not(:has(li))').closest(".represent_wrap").hide();
});

Solution

  • Firstly the logic you have seems backwards to what you describe - you're hiding the p element if there are multiple li elements found, not if there are none. Secondly, closest() looks at parent elements, where as the p is a sibling of the div, so you'd need to use prev() instead. Try this:

    $('.clients').each(function() {
        var $ul = $(this);
        if (!$('li', $ul).length) {
            $ul.closest('.clients_wrap').prev('p').hide();
        }
    });