If one of two elements exists, do something

eozzy picture eozzy · Dec 14, 2009 · Viewed 58.8k times · Source

I currently do this to check if one of two elements exists:

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

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

Answer

micahwittman picture micahwittman · Dec 14, 2009
if ($(".element1").is('*') || $(".element2").is('*')) {
    // code
}

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

if ($(".element1, .element2").is('*')) {
    // code
}