더북(TheBook)

4.4.2 부모와 자식 태그 찾기

HTML 태그끼리는 서로 부모 자식 관계를 가집니다. DOM에서도 어떤 태그의 부모나 자식 태그를 찾을 수 있습니다. bubbling.html 파일의 script 태그를 다음과 같이 수정합니다.

bubbling.html

<script>
console.log(document.querySelector('td').parentNode); // tr 태그
console.log(document.querySelector('tr').children); // [td, td, td]
</script>

tr 태그의 부모는 table 태그입니다. 현재 태그의 부모 태그를 찾고 싶을 때는 parentNode 속성을 사용합니다. 자식 태그는 children 속성으로 찾습니다. 자식 태그는 여러 개일 수 있으므로 children 속성의 값은 배열 모양의 객체가 됩니다. 단, 배열은 아니고 2.6.3절에서 배운 유사 배열 객체입니다. HTMLCollection이 이 객체의 이름입니다.

table에서 td 태그를 찾으려면 어떻게 해야 할까요? table의 자식은 tr이고, tr의 자식은 td이니 children을 연달아 두 번 사용하면 됩니다.

console.log(document.querySelector('table').children.children); // [td, td, td]
신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.