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.
'JAVASCRIPT > 소스코드' 카테고리의 다른 글
javascript 숫자 4단위 한글로 변환 (0) | 2014.09.16 |
---|---|
HTML에서 input박스에 글자 입력시 Byte체크 (0) | 2014.09.16 |
입력된 글자의 Byte 를 보여주는 스크립트 (0) | 2014.09.16 |
JAVASCRIPT_[ 자료형 검사시 유의사항(typeof / constructor) ] (0) | 2014.09.11 |
jQuery API: Manipulation, Events, Effects, Internals, Utilities (0) | 2014.08.19 |
javascript indexOf 함수, lastIndexOf 함수, 문자열, array 특정 위치값 가져오기 (0) | 2014.08.19 |
자바스크립트 for문으로 변수 생성 (0) | 2014.08.08 |
javascript for문 (0) | 2014.08.08 |