Jun 26, 2010

jQuery Determine Elements are Exist



As you know that, jQuery can be do that:
$("div").find("a").attr("href", "http://www.google.com").css("color", "#f00");

$("div") function return jQuery object, find() function also resturn jQuery object, so you can call jQuery function and call jQuery function again in one statement.

It is a problem to determine html elements are exist, because jQuery never return null. Below statement cannot check elements are exist.
if ($("div#sample") != null){
    //do something
} else {
   alert("not exist");
}

Javascipt never run 'alert("not exist");' statement, because $("div#sample") never return null.

How to determine elements are exist? You can call size() function to check.
if ($("div#sample").size() > 0){
    //do something
} else {
    alert("not exist");
}

if size() return zero, that meaning jQuery cannot find some elements.

Use javascript length properties also can do that:
if ($("div#sample").length > 0){
    //do something
} else {
    alert("not exist");
}

if length properties equal zero, that meaning jQuery cannot find some elements.


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code