document.getElementById로 요소 접근하기
요소에 id 속성이 지정되어 있다면, document.getElementById를 사용하면 문서 어디에 있든 해당 요소를 빠르게 찾을 수 있습니다.
단, HTML 내 id 값은 유일해야 하며, 동일한 id가 여러 개 존재하면 결과가 예측 불가능해집니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>DOM 탐색 예제</title>
</head>
<body>
<section id="user-profile">
<h2>사용자 프로필</h2>
<p>이름: <span id="user-name">Alice</span></p>
</section>
<script>
// id가 'user-name'인 요소를 가져와 텍스트를 변경합니다.
const nameElem = document.getElementById('user-name');
nameElem.textContent = 'Bob';
// 결과: 사용자 프로필의 이름이 "Bob"으로 변경됩니다.
</script>
</body>
</html>
브라우저는 HTML 파일 내에서 자동으로 id와 같은 이름의 전역 변수를 생성하지만, 이러한 전역 변수는 네임스페이스 충돌의 위험이 있으므로 document.getElementById를 사용하는 것이 안전합니다.
CSS 선택자를 이용한 검색: querySelector와 querySelectorAll
querySelector
querySelector는 지정한 CSS 선택자와 일치하는 첫 번째 요소를 반환합니다.
문서 전체뿐 아니라 특정 요소의 하위에서도 사용할 수 있습니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>QuerySelector 예제</title>
</head>
<body>
<ul class="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
// 클래스 'menu'를 가진 ul 요소 내에서 첫 번째 li를 선택합니다.
const firstItem = document.querySelector('.menu > li');
firstItem.style.color = 'blue'; // 첫 번째 메뉴 항목의 글자색을 파란색으로 변경
</script>
</body>
</html>
querySelectorAll
querySelectorAll은 지정한 CSS 선택자와 일치하는 모든 요소를 반환하며, 결과는 정적(NodeList) 컬렉션입니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>QuerySelectorAll 예제</title>
</head>
<body>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<script>
// 클래스 'item'에 해당하는 모든 요소를 선택합니다.
const items = document.querySelectorAll('.item');
items.forEach((el, index) => {
el.style.backgroundColor = index % 2 === 0 ? '#f0f0f0' : '#d0d0d0';
});
// 각 요소의 배경색을 교대로 지정합니다.
</script>
</body>
</html>
querySelectorAll은 정적 컬렉션을 반환하므로, 이후 DOM에 요소가 추가되어도 컬렉션은 갱신되지 않습니다. 반면, getElementsByTagName이나 getElementsByClassName은 살아있는(live) 컬렉션을 반환합니다.
고급 DOM 탐색 메서드
matches
matches 메서드는 특정 요소가 주어진 CSS 선택자와 일치하는지 여부를 반환합니다.
이를 통해 배열 등의 컬렉션을 순회하면서 원하는 조건에 맞는 요소만 필터링할 수 있습니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>matches 예제</title>
</head>
<body>
<a href="document.pdf">PDF 문서</a>
<a href="image.png">이미지</a>
<a href="report.pdf">보고서</a>
<script>
const links = document.querySelectorAll('a');
links.forEach(link => {
if (link.matches('a[href$="pdf"]')) { // href가 "pdf"로 끝나는 요소
console.log("PDF 링크:", link.href);
}
});
// 결과: PDF 문서와 보고서의 링크가 출력됩니다.
</script>
</body>
</html>
closest
closest 메서드는 선택한 요소부터 시작해, 자신을 포함하여 조상 요소 중 주어진 CSS 선택자와 일치하는 가장 가까운 요소를 반환합니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>closest 예제</title>
</head>
<body>
<div class="container">
<section>
<article class="post">
<p>포스트 내용</p>
</article>
</section>
</div>
<script>
// <p> 요소를 선택하고, 가장 가까운 조상 중 클래스가 "container"인 요소를 찾습니다.
const paragraph = document.querySelector('article.post p');
const container = paragraph.closest('.container');
container.style.border = "2px solid green";
// 결과: container 요소에 녹색 테두리가 적용됩니다.
</script>
</body>
</html>
전통적인 DOM 검색 메서드: getElementsBy* 계열
getElementsByTagName, getElementsByClassName, getElementsByName 등은 오래된 DOM 검색 메서드로, 요소를 배열과 유사한 실시간(live) 컬렉션으로 반환합니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>getElementsByTagName 예제</title>
</head>
<body>
<div>첫 번째 DIV</div>
<div>두 번째 DIV</div>
<script>
const divCollection = document.getElementsByTagName('div');
console.log("DIV 요소 개수:", divCollection.length); // 2
// 새로운 div를 추가해도 컬렉션은 자동으로 갱신됩니다.
const newDiv = document.createElement('div');
newDiv.textContent = "세 번째 DIV";
document.body.append(newDiv);
console.log("갱신된 DIV 요소 개수:", divCollection.length); // 3
</script>
</body>
</html>
요소 포함 여부: contains
DOM 노드 간의 관계를 쉽게 확인할 수 있는 메서드로 contains가 있습니다. 이 메서드는 특정 요소가 다른 요소의 자손인지(또는 동일한 요소인지)를 검사합니다.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>contains 예제</title>
</head>
<body>
<div id="parent">
<p>자식 요소</p>
</div>
<script>
const parentElem = document.getElementById("parent");
const childElem = parentElem.querySelector("p");
console.log(parentElem.contains(childElem)); // true
console.log(childElem.contains(parentElem)); // false
// 자기 자신도 포함합니다.
console.log(parentElem.contains(parentElem)); // true
</script>
</body>
</html>
'브라우저' 카테고리의 다른 글
HTML 속성 vs DOM 프로퍼티 (0) | 2025.02.19 |
---|---|
DOM 노드 마스터하기: 프로퍼티 탐구와 실전 활용법 (0) | 2025.02.19 |
DOM 트리 탐험: 웹 페이지 구조를 자유자재로 다루는 방법 (0) | 2025.02.19 |
DOM 트리의 모든 것: HTML에서 브라우저 렌더링까지 (0) | 2025.02.19 |
브라우저 환경 (0) | 2025.02.19 |