Language/JQuery
[Javascript] DOM 객체 ID 존재여부 확인하기
과일가게 개발자
2016. 12. 6. 15:41
반응형
자바스크립트를 이용해 페이지내에서 특정 DOM 객체가 존재하는지 확인해야 할 필요가 가끔 있다.
이럴때는 DOM 객체에 ID를 부여하고 해당 ID를 체크하면 된다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM ID Check</title>
<script type="text/javascript">
window.onload = function(){
// 자바스크립트
if(document.getElementById("test")){
console.log("해당 객체 존재함");
}else{
console.log("해당 객체 존재안함");
}
// jQuery
if($("#test").length > 0){
console.log("jquery : 해당 객체 존재함");
}else{
console.log("jquery : 해당 객체 존재안함");
}
}
</script>
</head>
<body>
<input type="text" name="test" id="test" value="">
</body>
</html>
jQuery에서는 ID가 존재하지 않을경우 length 로 0을 리턴한다.