views:

248

answers:

3

I currently do this to check if an elements exists:

if ($(".element1").length > 0 || $(".element2").length > 0 {
  ...stuff...
}

Is there a better way to rewrite the same? I mean, ".length" the same as ".length > 0" ?

Thanks

+3  A: 
if ($(".element1").is('*') || $(".element2").is('*')) {
  ...stuff...
}

EDIT (per comment) Select elements by multiple classes in one call:

if ($(".element1, .element2").is('*') {
  ...stuff...
}
micahwittman
Note that you can also combine the two selectors into one like so: `$(".element1, .element2")`.
bcat
Is ".is()" the same as ".length > 0"? Whats the difference, if any?
Nimbuz
Nimbuz, good post on use of .is() - http://www.bennadel.com/blog/1725-jQuery-s-is-Method-Checks-For-Any-Matching-Elements.htm
micahwittman
The SO Question Vincent linked to covers the topic thoroughly - good read.
micahwittman
+1  A: 

You might find this question answers your question.

Vincent Ramdhanie
A: 
if ( $('#myDiv')[0] ) { //do something }

..works best!

Found here.

Nimbuz