Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If one of two elements exists, do something

Tags:

jquery

exists

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?

like image 649
eozzy Avatar asked Dec 14 '09 05:12

eozzy


3 Answers

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

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

if ($(".element1, .element2").is('*')) {
    // code
}
like image 77
micahwittman Avatar answered Nov 15 '22 04:11

micahwittman


if ( $('#myDiv')[0] ) { //do something }

..works best!

Found here.

like image 29
eozzy Avatar answered Nov 15 '22 04:11

eozzy


All jQuery elements have the .length property. You can just go:

if ($('img').length) // Implies: If this element exists..

http://jqueryfordesigners.com/element-exists/

like image 16
Aaron Avatar answered Nov 15 '22 02:11

Aaron