dennismonsewicz
dennismonsewicz

Reputation: 25542

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.

Upvotes: 0

Views: 85

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

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

Upvotes: 1

kvn
kvn

Reputation: 2300

Assuming that you want to select #agency-header-toolbar which are not empty. It is more simpler to use

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

Upvotes: 1

Related Questions