πŸ‹DOM Traversing

hayoungΒ·2023λ…„ 3μ›” 27일
0

JavaScript-DOM

λͺ©λ‘ 보기
5/5
post-thumbnail

πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦1. Going downwards: children 탐색

const h1 = document.querySelector("h1");

// (1) h1 μžμ‹ 쀑 highlight class의 μžμ‹(λ“€) μ°ΎκΈ°
console.log(h1.querySelectorAll(".highlight"));
// NodeList(2) [span.highlight, span.highlight]

// (2) h1의 all 'direct' children
console.log(h1.children);
// HTMLCollection(3) [span.highlight, br, span.highlight]

// (3) h1의 첫번째 μžμ‹ μŠ€νƒ€μΌ λ°”κΎΈκΈ°
h1.firstElementChild.style.color = "orange";

πŸ‘©β€πŸ‘§β€πŸ‘¦2. Going upwards: parents 탐색

  • closest: finds parents (upwards)
  • querySelector: finds children (downwards)
// (1) h1의 parentNode, parentElement
console.log(h1.parentNode); //<div class="header__title"></div>
console.log(h1.parentElement); //<div class="header__title"></div>

// (2) closest
// h1μ—μ„œ <μœ„λ‘œ> 제일 κ°€κΉŒμ΄ μžˆλŠ” header class μŠ€νƒ€μΌ λ³€κ²½
h1.closest(".header").style.background = "var(--gradient-secondary)";
// h1μ—μ„œ <μœ„λ‘œ> 제일 κ°€κΉŒμ΄ μžˆλŠ” h1의 μŠ€νƒ€μΌ λ³€κ²½
h1.closest("h1").style.background = "var(--gradient-primary)";

πŸ‘¬3. Going sideways: siblings (only direct siblings) 탐색

// (1) h1의 μ•ž, λ’€ ν˜•μ œ element 탐색
console.log(h1.previousElementSibling);
console.log(h1.nextElementSibling);

// (2)h1의 all siblings (μžκΈ°μžμ‹  포함)
console.log(h1.parentElement.children);

// (3)h1의 siblings 쀑에 μžκΈ°μžμ‹ μ„ μ œμ™Έν•˜κ³  μŠ€νƒ€μΌ 변경해보기
[...h1.parentElement.children].forEach(function (el) {
  if (el !== h1) {
    el.style.transform = "scale(0.5)";
  }
});
profile
Persistence pays off.

0개의 λŒ“κΈ€