jQuery show element if not empty

I have the following jQuery code:

var agencyToolbar = $('#agency-header-toolbar');
if ($(":not(:empty)", agencyToolbar)) {
    agencyToolbar.show();
}

The code above works, but I wasn't sure if it's a proper way to use a jQuery selector.


Your code will always fire the show as $(":not(:empty)", agencyToolbar) creates a jQuery object which is never null so is always "truthy".

You wanted to use is (which returns a boolean result) like

if (agencyToolbar.is(':not(:empty))')){

or use a single selector like

$("#agency-header-toolbar:not(:empty)").show();

If you need it to be a tad faster, do the id selector first as its own operation, then filter it with not()

$("#agency-header-toolbar").not(":empty").show();