Thursday, April 14, 2011

jQuery - check element if it's existed

This is the correct way of doing this

if($('.myClass').length > 0) {
    // blah ...
}

Some people ask, why the following doesn't work??

if($('.myClass')) {
    // blah ...
}

Well, it's because jQuery selector always returns you an Object. 

===

Of course, if you are using plain javascript, then it is correct.  For example,

var home = document.getElementById("home");

if(home) {
  // blah ...
}

No comments:

Post a Comment