0

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.

2
  • 1
    Maybe you want to simply ask if ($('#agency-header-toolbar')) { ... Commented Apr 16, 2015 at 19:28
  • @zed: Your code will always result in "truthy". Same mistake as the original code. You probably meant to add .length == 0 as in $('#agency-header-toolbar').length === 0 or !$('#agency-header-toolbar').length. Commented Apr 17, 2015 at 8:56

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.