728x90
반응형

 

http://jquery.open2space.com/node/44


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.

- opencode.co.kr - 


728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,