요소(Element)에 동적인 처리가 요구되는 경우 해당 요소(Element)가 존재하는지 먼저 확인 할 필요가 있습니다. 웹사이트를 개발하다보면 여러 요소들을 동적으로 생성하고 제거하는 등의 제어를 하는 경우가 많습니다. 이런 프로세스 속에서 Ajax 를 사용하여 데이터를 리턴 받은 후 해당 데이터를 특정 요소에 넣기전에 해당 요소가 존재하지 않는다면 오류를 일으키게 됩니다. 오류를 무시해도 무관하다면 상관없지만 세밀한 프로세스들이 작동하는 웹페이지라면 이런 오류 하나에도 원치 않는 결과를 만들어 낼 수 있습니다.
사소할 수도 있지만 위험 요소를 막기 위한 방어코드로 활용한다면 유용할 것 입니다.
Javascript
jQuery
전체 테스트 코드
사소할 수도 있지만 위험 요소를 막기 위한 방어코드로 활용한다면 유용할 것 입니다.
Javascript
|
1
2
3
4
5
6
7
|
<script>if (document.getElementById('helloA')) { document.getElementById('helloA').innerHTML = '안녕하세요';} else { console.log('[Javascript] helloA is not exist');}</script> |
jQuery
|
1
2
3
4
5
6
7
|
<script>if ($('#helloB').length) { $('#helloB').text('안녕하세요');} else { console.log('[jQuery] helloB is not exist');}</script> |
전체 테스트 코드
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!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>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> |

