tags:

views:

42

answers:

2

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?

+6  A: 

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.

Nick Craver
What? `.length` gives 0 if there are no elements.
strager
@strager - I'm not following, he wants to show it only if the other element's on the page, so `.length` would be greater than `0` meaning a `true` to the `if()`. If it's not there, `.length == 0` and the `.show()` doesn't run.
Nick Craver
if(document.getElementById('some_div')){$('#another_div').show();}
pferdefleisch
Thanks Nick this is exacly what i was looking for
Matt
"`.length` returns the number of results the selector found, if it found any it's greater than 0 (`true`) and `false` otherwise." This reads, "If the number of results is greater than 0, `.length` the number of results (which evaluates to `true`); otherwise, it returns `false`." This is wrong.
strager
@strager - Sorry if it's not 100% clear from the first half of the sentence, `0 ~= false` just as `>0 ~= true` in JavaScript. You may treat `0` as `false` in the case of an `if` statement.
Nick Craver
+1  A: 

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.

strager
Why would you ever want to use an iterator for a single element?
Gert G
@Gert G, It's a way. Not necessarily the best way. This can be chained and the `.length` method cannot (easily) be chained, for example.
strager
@strager - But it's overkill for what the OP was asking. ;)
Gert G