2009年9月24日 星期四

JQuery How to check if an element exists

A common question comes up very frequently - "how do I know if XXX exists". The XXX could be a particular DIV with a class, or it might be an ID. The issue is common enough that it has been listed in the jQuery FAQs (http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_...).

Some people attempt to just check the jQuery object for the specified selector:


//This will not work

if ( $("#myid") ) {

//do something

}


This will fail. The jQuery object will ALWAYS return something. When we say $( ) we are asking for a jQuery object. So we get one back. The above code will always equate to TRUE.

The jQuery object contains a list/array of the elements that match our selector. So we can ask for the length of this internal list. The jQuery kindly exposes this length for us as the .length property. If the length is greater than zero then we have at least one object that matches our selector.


if ( $("#myid").length > 0 ) {

//do something

}


So now the only question is what we are testing. This is defined by the selector we use. If we want to know if a particular ID exists, we would use a selector of "#theID". If we were trying to determine if a DIV with a particular class existed, we would use the selector of "div.theClass".


if ( $("#theID").length > 0 ) { alert("The ID exists"); }

if ( $("div.theClass").length > 0 ) { alert("The DIV exists"); }


In this way we can check to see if ANY element exists.

沒有留言:

wibiya widget