开发者

jQuery to hide a parent if the child has no text

开发者 https://www.devze.com 2023-02-10 22:58 出处:网络
I have this mar开发者_JS百科kup: <li class=\"GRID_ITEM\" id=\"123\"> <img class=\"imgUrl\" src=\"search_logo_big.png\">

I have this mar开发者_JS百科kup:

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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消