Document.getElementById()
id
속성의 값은 HTML에서 고유하고 유일해야 하기 때문에 이 함수를 사용해서 요소를 빠르게 찾을 때 유용합니다.
구문
document.getElementById(id);
매개변수
id |
찾으려는 요소의 id 속성의 값입니다. 이 값은 대소문자를 구분하는 문자열입니다. |
---|
반환 값
HTML에서 id
속성의 값은 고유하고 유일해야 하지만,
동일한 id
속성의 값을 두 개 이상 가진 요소가 존재하면 DOM 트리 순서로 첫 번째 요소 객체만 반환합니다. 에러는 발생하지 않습니다.
예제
<!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");
ele.style.color = newColor;
}
</script>
<button type="button" onclick="changeColor('red');">빨간색으로 변신</button>
<button type="button" onclick="changeColor('blue');">파란색으로 변신</button>
</body>
</html>
환영합니다. 반갑습니다!
주의할 점
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="btn4" 요소는 없습니다. */
const btn4 = document.getElementById("btn-4"); // id="btn4"와 일치하는 요소를 찾습니다.
// btn4는 요소 객체가 아닌 null이 됩니다.
// Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
btn4.addEventListener("click", () => {
// ...
});
</script>
</body>
</html>
이 예제에서 변수 btn4
는 null
이 됩니다.
document.getElementById("btn-4")
로 일치하는 요소를 찾지만, 일치하는 요소가 없기 때문에 null
을 반환하기 때문입니다.
버튼을 클릭할 때 발생하는 이벤트를 수신하기 위해서 이벤트 수신 함수인 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="btn4" 요소는 없습니다. */
const btn4 = document.getElementById("btn-4"); // id="btn4"와 일치하는 요소를 찾습니다.
// btn4는 요소 객체가 아닌 null이 됩니다.
if (btn4) {
btn4.addEventListener("click", () => {
// ...
});
} else {
console.warn("아이디가 'btn4'인 요소를 찾을 수 없습니다.");
}
</script>
</body>
</html>
이 예제에서는 변수 btn4
가 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="btn4" 요소는 없습니다. */
const btn4 = document.getElementById("btn-4"); // id="btn4"와 일치하는 요소를 찾습니다.
// btn4는 요소 객체가 아닌 null이 됩니다.
try {
btn4.addEventListener("click", () => {
// ...
});
} catch (error) {
console.warn("아이디가 btn4인 요소를 찾을 수 없습니다.");
}
</script>
</body>
</html>
찾으려는 요소의 id
속성의 값은 대소문자 구분
getElementById(id)
함수의 매개변수 id
는 대소문자를 구분하는 문자열입니다.
<div id="user-info"></div>
id
는 대소문자를 구분하는 문자열입니다.
getElementById("User-id");
getElementById("User-Id");
getElementById("USER-ID");
id
는 대소문자가 정확히 일치해야 합니다.
getElementById("user-id");
getElementById()
는 오직 document
객체의 메서드
getElementById()
는 오직 document
객체의 메서드입니다. parentNode
객체나 parentElement
객체 등 부모 요소 객체에 사용할 수 없습니다.
<div id="container">
<div id="child"></div>
</div>
parentNode
객체나 parentElement
객체 등 부모 요소 객체에 사용할 수 없습니다.
const container = document.getElementById("container");
// 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 |