[JS] DOM Traversing

Minsu Han·2022년 8월 29일

Javascript

목록 보기
1/7
  • DOM 트리에서 요소의 부모, 자식, 형제 요소에 접근하기
const h1 = document.querySelector('h1');

// Going downwards: child
console.log(h1.querySelectorAll('.highlight'));
console.log(h1.childNodes);	// text, comment 등 Node에 해당하는 모든 것들을 포함
console.log(h1.children);	// text, comment 등을 포함하지 않음
h1.firstElementChild.style.color = 'white';
h1.lastElementChild.style.color = 'orangered';

// Going upwards: parents
console.log(h1.parentNode);
console.log(h1.parentElement);

// 부모 요소 중 키워드에 해당하는 요소들 중 가장 가까운 요소
h1.closest('.header').style.background = 'var(--gradient-secondary)';
// var(...)는 css 파일에서의 변수
h1.closest('h1').style.background = 'var(--gradient-primary)';

// Going sideways: siblings
console.log(h1.previousElementSibling);
console.log(h1.nextElementSibling);

console.log(h1.previousSibling);	// text, comment 등 Node도 확인
console.log(h1.nextSibling);

console.log(h1.parentElement.children);
// h1의 부모 요소의 자식 요소들 중 h1을 제외하고 scale(0.5) style을 적용하기
[...h1.parentElement.children].forEach(function (el) {
  if (el !== h1) el.style.transform = 'scale(0.5)';
});
profile
기록하기

0개의 댓글