프로그램 언어/JavaScript Dom Part

[J.S_DOM] 5-1. 부모 노드 접근 실습 예제

알케이88 2025. 8. 9. 00:02

 

5.1 부모 노드에 접근하기

<!-- 📘 예제 1: parentElement로 부모 요소 두 단계 접근하기 -->
<!-- 💡 parentElement를 사용하면 현재 요소에서 상위 요소로 계속 올라갈 수 있음. -->
    <section id="section">
        <article>
            <h2 id="title">제목</h2>
        </article>
    </section>

    <script>
        const title = document.getElementById("title");
        console.log(title.parentElement); // 👉 <article>...</article>
        console.log(title.parentElement.parentElement); // 👉 <section id="section">...</section>
    </script>

<!-- 👉 콘솔 출력: -->
<article>...</article>
<section id="section">...</section>

<!-- 📘 예제 2: parentNode로 부모에 스타일 적용 -->
<!-- 💡 부모 노드에 직접 접근해 스타일을 변경할 수 있음.. -->
    <div class="wrapper">
        <span id="text">Hello</span>
    </div>

    <script>
        const text = document.getElementById("text");
        const parent = text.parentNode;
        parent.style.backgroundColor = "lightblue";
    </script>

<!-- 👉 실행 결과: -->
<!-- div.wrapper에 배경색 lightblue 적용됨 -->

5.2 자식 노드에 접근하기

<!-- 📘 예제 1: children을 이용해 li 요소에 접근 -->
<!-- 💡 공백 없이 자식 요소만 가져올 때는 children이 가장 안전 -->
    <ul id="list">
        <li>🍎</li>
        <li>🍌</li>
        <li>🍇</li>
    </ul>

    <script>
        const list = document.getElementById("list");
        console.log(list.children[0].textContent); // 👉 "🍎"
        console.log(list.children[2].textContent); // 👉 "🍇"
    </script>

<!-- 👉 콘솔 출력: -->
🍎
🍇


<!-- 📘 예제 2: children 반복해서 태그 이름 출력 -->
<!-- 💡 pchildren은 HTMLCollection이므로 반복 처리에 적합 -->
    <div id="box">
        <h3>제목</h3>
        <p>내용</p>
    </div>

    <script>
        const box = document.getElementById("box");
        const children = Array.from(box.children);
        children.forEach(child => {
            console.log(child.tagName); // 👉 H3, P
        });
    </script>

<!-- 👉 콘솔 출력: -->
CSS

H3  
P

5.3 형제 노드에 접근하기

<!-- 📘 예제 1: nextElementSibling과 previousElementSibling -->
<!-- 💡 텍스트 노드 제외, 진짜 "형제 요소"만 탐색 가능 -->
    <nav>
        <a id="link1" href="#">Home</a>
        <a id="link2" href="#">About</a>
        <a id="link3" href="#">Contact</a>
    </nav>

    <script>
        const link2 = document.getElementById("link2");
        console.log(link2.previousElementSibling.textContent); // 👉 "Home"
        console.log(link2.nextElementSibling.textContent);     // 👉 "Contact"
    </script>

<!-- 👉 콘솔 출력: -->
nginx
Home  
Contact


<!-- 📘 예제 1: parentElement로 부모 요소 두 단계 접근하기 -->
<!-- 💡 parentElement를 사용하면 현재 요소에서 상위 요소로 계속 올라갈 수 있음. -->
    <div>
        <h1>타이틀</h1>
        <p id="desc">설명입니다</p>
    </div>

    <script>
        const desc = document.getElementById("desc");
        const title = desc.previousElementSibling;
        title.style.color = "red"; // 👉 <h1> 요소에 스타일 적용
    </script>

<!-- 👉 실행 결과: -->
<!-- 타이틀 <- 빨간색 텍스트로 출력 -->