Matt Elhotiby
Matt Elhotiby

Reputation: 44066

Conditionally showing an element in jQuery

I want to make a div visible if there is an element on the page. For example:

If ('#some_div') is on the page, I want to do a ('#another_div').show();

What's the syntax to make this happen?

Upvotes: 2

Views: 410

Answers (2)

strager
strager

Reputation: 90012

In addition to checking for .length, you can use .each:

$('#some_div').each(function () {
    $('#another_div').show();
});

Just make sure there is only one element in your initial selector.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630409

You can use .length, like this:

if($('#some_div').length) $('#another_div').show();

.length returns the number of results the selector found, if it found any it's greater than 0 (true) and false otherwise.


Alternatively if you need to hide it, e.g. so it works both ways, you can use .toggle(bool) like this:

$('#another_div').toggle($('#some_div').length > 0);

This works regardless of the initial state, it'll hide it if #some_div isn't not there, and show it if it is.

Upvotes: 6

Related Questions