kinet
kinet

Reputation: 1780

jQuery to hide a parent if the child has no text

I have this markup:

<li class="GRID_ITEM" id="123">
    <img class="imgUrl" src="search_logo_big.png">
    <div class="title"></div>
</li>

I'd like to hide li.GRID_ITEM if div.title has no text.

I don't know how to do this in JQ. Thanks!!!

Upvotes: 1

Views: 2806

Answers (1)

David Tang
David Tang

Reputation: 93664

There's the :empty selector:

$('li.GRID_ITEM:has(div.title:empty)').hide();

But be warned that :empty strictly means no text (including whitespace) and no child elements. If you want to handle cases including whitespace or child elements, then use:

$('li.GRID_ITEM').filter(function () {
    return $.trim($(this).find('div.title').text()).length == 0;
}).hide();

As Šime Vidas points out, this will also hide any parent that doesn't have the child element at all. If that's not what you wanted, you can try this variation which additionally checks if the child element exists:

$('li.GRID_ITEM').filter(function () {
    var title = $(this).find('div.title');
    return title.length && $.trim(title.text()).length == 0;
}).hide();

Upvotes: 7

Related Questions