정의 및 사용 방법
id 속성의 값은 HTML에서 고유하고 유일해야 하기 때문에 이 함수를 사용해서 요소를 빠르게 찾을 때 유용합니다.
기본 예제
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>getElementById() 예제</title>
</head>
<body>
<p id="hello">환영합니다. 반갑습니다!</p>
<script>
const changeColor = newColor => {
const ele = document.getElementById("hello"); // id="hello"와 일치하는 요소를 찾습니다.
ele.style.color = newColor;
}
</script>
<button type="button" onclick="changeColor('red');">빨간색으로 변신</button>
<button type="button" onclick="changeColor('blue');">파란색으로 변신</button>
</body>
</html>
환영합니다. 반갑습니다!
구문
document.getElementById(id);
매개변수
id |
찾으려는 요소의 id 속성의 값입니다. 이 값은 대소문자를 구분하는 문자열입니다. |
|---|
반환 값
주의할 점
getElementById() 함수를 사용할 때에는 몇 가지 주의할 점이 있습니다.
찾으려는 요소가 없을 때 에러 발생 예방
getElementById() 함수로 찾으려는 요소가 없으면 null을 반환합니다.
다음과 같은 예제 상황에서는 에러를 발생시킵니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>찾으려는 요소가 없을 때 에러 발생</title>
</head>
<body>
<button type="button" id="btn1">btn1 버튼</button>
<button type="button" id="btn2">btn2 버튼</button>
<button type="button" id="btn3">btn3 버튼</button>
<script>
/* id="btn-4" 요소는 없습니다. */
const eleBtn4 = document.getElementById("btn-4"); // id="btn-4"와 일치하는 요소를 찾습니다.
// eleBtn4는 요소 객체가 아닌 null이 됩니다.
// Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
eleBtn4.addEventListener("click", () => {
// ...
});
</script>
</body>
</html>
버튼을 클릭할 때 발생하는 이벤트를 수신하기 위해서 이벤트 수신 함수인 addEventListener()는 이벤트를 지원하는 객체(예를 들어 요소 객체나 Document, window 객체 등)를 대상으로 하는데, null은 이벤트를 지원하는 객체가 아니기 때문에 TypeError를 발생시킵니다.
이러한 상황은 흔히 있을 수 있습니다.
예제의 경우는 HTML 문서 내에서 인라인으로 HTML 요소와 자바스크립트를 한 눈에 파악할 수 있게 작성했지만, 자바스크립트를 파일로 분리해서 작성할 경우가 해당할 수 있습니다. 개발자가 한 눈에 쉽게 파악할 수 없기 때문입니다.
이러한 에러를 발생시킬 수 있는 상황을 대비해서 다음과 같이 코드를 작성하는 것이 에러 예방에 도움이 됩니다.
if() 문
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>찾으려는 요소가 없을 때 에러 발생</title>
</head>
<body>
<button type="button" id="btn1">btn1 버튼</button>
<button type="button" id="btn2">btn2 버튼</button>
<button type="button" id="btn3">btn3 버튼</button>
<script>
/* id="btn-4" 요소는 없습니다. */
const eleBtn4 = document.getElementById("btn-4"); // id="btn-4"와 일치하는 요소를 찾습니다.
// eleBtn4는 요소 객체가 아닌 null이 됩니다.
if (eleBtn4) {
eleBtn4.addEventListener("click", () => {
// ...
});
} else {
console.warn("id가 'btn-4'인 요소를 찾을 수 없습니다.");
}
</script>
</body>
</html>
이 예제에서는 변수 eleBtn4가 null인지를 if() 문으로 평가해서 true이면 코드를 실행하고, false이면 콘솔에 경고문구를 출력하게 하였습니다.
if() 문 대신 try..catch 문을 사용할 수도 있습니다.
try..catch 문
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>찾으려는 요소가 없을 때 에러 발생</title>
</head>
<body>
<button type="button" id="btn1">btn1 버튼</button>
<button type="button" id="btn2">btn2 버튼</button>
<button type="button" id="btn3">btn3 버튼</button>
<script>
/* id="btn-4" 요소는 없습니다. */
const btn4 = document.getElementById("btn-4"); // id="btn-4"와 일치하는 요소를 찾습니다.
// btn4는 요소 객체가 아닌 null이 됩니다.
try {
btn4.addEventListener("click", () => {
// ...
});
} catch (error) {
console.warn("id가 'btn-4'인 요소를 찾을 수 없습니다.");
}
</script>
</body>
</html>
try..catch 문을 사용할 수도 있지만, 일반적으로는 if() 문으로 반환값이 null인지 확인하는 방법이 더 선호됩니다.
에러가 발생한 후 처리하는 것보다, 에러가 발생하기 전에 미리 예방할 수 있기 때문입니다.
찾으려는 요소의 id 속성의 값은 대소문자 구분
getElementById(id) 함수의 매개변수 id는 대소문자를 구분하는 문자열입니다.
<div id="user-id"></div>
id는 대소문자를 구분하는 문자열입니다.
getElementById("User-id");
getElementById("User-Id");
getElementById("USER-ID");
id는 대소문자가 정확히 일치해야 합니다.
getElementById("user-id");
getElementById()는 오직 document 객체의 메서드
getElementById()는 HTML 문서 전체를 기준으로 요소를 찾는 document 전용 메서드입니다.
따라서 parentNode나 parentElement 속성(Property)을 통해 접근 가능한 Element 객체에서는 사용할 수 없습니다.
<div id="container">
<div id="child"></div>
</div>
Element 객체에서는 사용할 수 없습니다.
const container = document.getElementById("container");
// id가 일치하는 요소를 찾아 Element 객체를 반환합니다.
// 'container'는 'document 객체'가 아니라 'Element 객체'입니다.
// Uncaught TypeError: container.getElementById is not a function
const child = container.getElementById("child");
getElementById()는 오직 document 객체의 메서드입니다.
const child = document.getElementById("child");
명세서
| 명세서 사양 | |
|---|---|
getElementById()
|
DOM Standard #ref-for-dom-nonelementparentnode-getelementbyid② |
브라우저 호환성
| 메서드 |
데스크탑 Chrome
|
데스크탑 Edge
|
데스크탑 Firefox
|
Safari
|
|---|---|---|---|---|
getElementById()
|
1 | 12 | 1 | 1 |