JAVASCRIPT/JQUERY/AJAX

[javascript-jQuery] 요소(Element) 존재 여부 확인

최고관리자
2018.07.04 13:21 10,186 0

본문

[jQuery] 요소(Element) 존재 여부 확인



요소(Element)에 동적인 처리가 요구되는 경우 해당 요소(Element)가 존재하는지 먼저 확인 할 필요가 있습니다. 웹사이트를 개발하다보면 여러 요소들을 동적으로 생성하고 제거하는 등의 제어를 하는 경우가 많습니다. 이런 프로세스 속에서 Ajax 를 사용하여 데이터를 리턴 받은 후 해당 데이터를 특정 요소에 넣기전에 해당 요소가 존재하지 않는다면 오류를 일으키게 됩니다. 오류를 무시해도 무관하다면 상관없지만 세밀한 프로세스들이 작동하는 웹페이지라면 이런 오류 하나에도 원치 않는 결과를 만들어 낼 수 있습니다.


사소할 수도 있지만 위험 요소를 막기 위한 방어코드로 활용한다면 유용할 것 입니다.


Javascript

<script>

if (document.getElementById('helloA')) {

  document.getElementById('helloA').innerHTML = '안녕하세요';

} else {

  console.log('[Javascript] helloA is not exist');

}

</script>


jQuery

<script>

if ($('#helloB').length) {

    $('#helloB').text('안녕하세요');

} else {

    console.log('[jQuery] helloB is not exist');

}

</script>


전체 테스트 코드

<!DOCTYPE html>

<html lang="ko-KR">

<head>

    <meta charset="uft-8">

    <title>요소(Element) 존재 여부 확인 테스트</title>

</head>

<body>

<div id="helloA"></div>

<div id="helloB"></div>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script>

if (document.getElementById('helloA')) {

    document.getElementById('helloA').innerHTML = '안녕하세요';

} else {

    console.log('[Javascript] helloA is not exist');

}

 

if ($('#helloB').length) {

    $('#helloB').text('안녕하세요');

} else {

    console.log('[jQuery] helloB is not exist');

}

</script>

</body>

</html>



출처 : http://vucket.com/index.php/topic/view/105

댓글목록 0

등록된 댓글이 없습니다.