01. 노드 접근 방법

양희준·2022년 2월 6일
0

DOM

목록 보기
1/8
post-thumbnail

📌 1-1 DOM이란?

Document Object Model라는 뜻이다.

💡 HTML 문서의 계층적 구조와 정보를 표현하며 이를 제어할 수 있는 API
💡 프로퍼티와 메소드를 제공하는 트리구조이다.

📌 1-2 프로퍼티와 메소드란?

  1. 프로퍼티 : 의미로는 속성으로 객체의 특징이다.
  2. 메소드 : 의미로는 행동으로 JavsScript에서는 함수로 된 프로퍼티이다.
const Object = {
    // 프로퍼티는 객체의 각각의 요소라고 생각해도 된다.
    property: "property",
    // 메소드는 프로퍼티이며 함수로된 프로퍼티를 메소드라고 한다.
    method: function() {
        console.log("method");
    }
}

📌 1-3 HTML 요소와 노드 객체란?

  1. HTML 요소 : HTML 문서를 구성하는 각각의 요소들로 시작 태그, 속성, 내용, 종료태그가 있다.

2. 노드 객체 : HTML요소를 DOM을 구성하는 요소로 변환한 것

📌 1-4 DOM 트리란?

노드 객체들로 구성된 트리 자료구조이다.

  1. 루트 노드 : 최상의 노드를 뜻한다.
    📋 document
  2. 부모 노드 : 노드간 계층에서 위에 있는 노드를 뜻한다.
    📋 body 태그는 div 태그의 부모 노드이다.
  3. 형제 노드 : 노드간 계층에서 같은 레벨에 있는 노드를 뜻한다.
    📋 li 태그들
  4. 자식 노드 : 노드간 계층에서 아래에 있는 노드를 뜻한다.
    📋 div 태그는 body태그의 자식 노드이다.
  5. 리프 노드 : 자식 노드가 없는 노드를 리프 노드라고 한다.
    📋 text

📌 1-5 노드의 타입 4가지

노드의 타입은 12가지가 있지만 제일 중요한 노드만 정리

  1. 문서 노드 : DOM트리의 최상단에 존재하는 루트 노드로써 document를 가리킨다.
    ① HTML 문서당 document 객체는 유일하다.
    ② document 객체는 DOM트리의 루트 노드로써 노드들에 접근하기 위한 진입점 역할을 수행한다.
  2. 요소 노드 : HTML 요소를 가리키는 객체이다.
    ① 요소 노드는 HTML간 요소간의 부자관계로 나타낼 수 있다.
    ② 문서의 구조를 표현한다.
    ③ 요소 노드는 HTML의 태그라고 생각해도 무관하다.
  3. 속성 노드 : HTML의 속성을 가리키는 객체이다.
    ① 속성 노드는 요소 노드와 연결되어 있다.
    ② 속성 노드를 참고하거나 변경하려면 먼저 요소 노드에 접근해야 한다.
    ③ 속성 노드는 부모 노드가 존재하지 않는다.
  4. 텍스트 노드 : HTML의 내용을 가리키는 객체이다.
    ① 텍스트 노드는 요소노드의 자식 노드이다.

📌 1-6 노드 프로토타입 상속 구조

프로토타입 체인 순서요소 노드 객체의 특성프로토타입 객체
1input 요소 객체HTMLInputElement
2HTML 요소 객체HTMLElement
3요소 객체Element
4노드 객체Node
5이벤트 객체EventTarget
6객체Object

① HTMLInputElement : input 태그만의 고유한 기능을 제공한다.
② HTMLElement : 모든 HTML의 태그의 공통적인 기능들을 제공한다.
③ Element : 요소 태그의 기능들을 제공한다.
④ Node : 노드 태그의 탐색등등 노드 태그와 관련된 기능들을 제공한다.
⑤ EventTarget : 이벤트 기능을 제공한다.
⑥ Object : JavaScript의 객체 프로토타입이다.

📃 메소드중 Element 메소드는 HTML요소만 반환하는 반면에 Node 메소드는 텍스트 노드도 같이 반환하는 경우가 있다. Element는 즉 요소 노드와 관련된 것이며 Node의 개념이 더 큰 개념이다.

📌 1-7 id를 이용해서 요소 노드 접근

🧩 Doucument.prototype.getElementById(id)

✔ id는 고유한 값으로 하나의 노드만 탐색한다.

<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul>
            <li id="red">Red</li>
            <li id="orange">Orange</li>
            <li id="yellow">Yellow</li>
        </ul>
    </body>
    <script>
        // id를 이용하여 요소 노드를 획득
        const $red = document.getElementById("red");
        console.log($red);
    </script>
</html>

📌 1-8 태그 이름을 이용해서 요소 노드 접근

🧩 Document.prototype.getElementsByTagNames(tag)
🧩 Element.prototype.getElementsByTagNames(tag)

✔ document에서 탐색을 시작하면 HTML전체를 확인한다.
✔ 요소 노드부터 시작하면 요소 노드의 자식노드부터 아래로 확인한다.

<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="color">
            <li id="red">Red</li>
            <li id="orange">Orange</li>
            <li id="yellow">Yellow</li>
        </ul>
        <ul id="animals">
            <li id="dog">Dog</li>
            <li id="cat">Cat</li>
        </ul>
    </body>
    <script>
        // document는 DOM 트리의 루트 노드로써 DOM전체에서 탐색한다.
        const $li = document.getElementsByTagName("li");
        const $animals = document.getElementById("animals");
        // id가 animals인 요소 노드부터 탐색한다.
        const $animalsli = $animals.getElementsByTagName("li");
        // 결과: HTMLCollection(5) [li#red, li#orange, li#yellow, li#dog ...]
        console.log($li);
        // 결과: HTMLCollection(2) [li#dog, li#cat, dog: li#dog, cat: li#cat]
        console.log($animalsli);
    </script>
</html>

📌 1-9 class를 이용해서 요소 노드 접근

🧩 Document.prototype.getElementsByClassName(className)
🧩 Element.prototype.getElementsByClassName(className)

✔ document에서 탐색을 시작하면 HTML전체를 확인한다.
✔ 요소 노드부터 시작하면 요소 노드의 자식노드부터 아래로 확인한다.

<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul class="color">
            <li class="color red">Red</li>
            <li class="color orange">Orange</li>
            <li class="color yellow">Yellow</li>
        </ul>
        <ul id="animals">
            <li class="animals dog">Dog</li>
            <li class="animals cat">Cat</li>
        </ul>
    </body>
    <script>
        // class 이름중 color가 들어가있는 모든 요소 노드 탐색
        const $color = document.getElementsByClassName("color");
        // class 이름중 color와 red가 들어가있는 모든 요소 노드 탐색
        const $red = document.getElementsByClassName("color red");
        // id가 animals인 요소 노드 탐색
        const $animals = document.getElementById("animals");
        /* id가 animals인 요소 노드의 자식중 
           class 이름에 animals가 들어가있는 요소 노드 탐색 */
        const $animalsli = $animals.getElementsByClassName("animals");
        // 결과 : HTMLCollection(4) [ul.color, li.color.red, li.color.orange ...]
        console.log($color);
        // 결과 : HTMLCollection [li.color.red]
        console.log($red);
        // 결과 : HTMLCollection(2) [li.animals.dog, li.animals.cat]
        console.log($animalsli);
    </script>
</html>

📌 1-10 CSS Selector를 이용한 요소 접근

🧩 Document.querySelector(selectors)
🧩 Element.querySelector(selectors)
🧩 Document.querySelectorAll(selectors)
🧩 Element.querySelectorAll(selectors)

✔ 제일 많이 사용하는 요소 노드 접근 방법
✔ querySelector는 조건에 맞는 첫번째 노드만 반환
✔ querySelectorAll은 조건에 맞는 모든 노드를 NodeList로 반환.
✔ document에서 탐색을 시작하면 HTML전체를 확인한다.
✔ 요소 노드부터 시작하면 요소 노드의 자식노드부터 아래로 확인한다.

/* 전체 선택자: 모든 요소를 선택 */
*
/* 태그 선택자: 모든 태그를 선택 */
li
/* id 선택자: id 값이 color인 요소 모두 선택 */
#color
/* class 선택자: class 값이 color인 요소 모두 선택 */
.color
/* 속성 선택자: input 요소 중 type 속성이 text인 요소 모두 선택 */
input[type=text]
/* 후손 선택자: ul 요소의 후손중 li 태그인 요소 모두 선택 */
ul li
/* 자식 선택자: ul 요소의 자식중 li 태그인 요소 모두 선택 */
ul > li
/* 인접 형제 선택자: div 요소의 형제 요소 중 span 이며 바로 뒤 요소 반환 */
div + span
/* 일반 형제 선택자: div 요소의 형제 요소 중에 span 모두 선택 */
div ~ span
/* 가상 클래스 선택자: 나중에 사용할 때 찾아보기 */
a:hover
/* 가상 요소 선택자: 나중에 사용할 때 찾아보기 */
a::before
<!DOCTYPE html>
<html lang="kr">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <ul id="nav-container1">
            <li class="nav1">nav1</li>
            <li class="nav2">nav2</li>
            <ul id="nav-container2">
                <li class="nav3">nav3</li>
                <li class="nav4">nav4</li>
            </ul>
        </ul>
        <input type="number" placeholder="number">
        <input type="text" placeholder="text">
        <input type="text" placeholder="text">
        <div class="form">
            <div></div>
            <span class="text1">Hello</span>
            <span class="text2">World</span>
        </div>
    </body>
    <script>
        // 모든 요소 노드 탐색
        const $all = document.querySelectorAll("*");
        // 모든 li 태그 요소만 탐색
        const $liTag = document.querySelectorAll("li");
        // id가 #nav-container1인 모든 요소 탐색
        const $navContaniner1 = document.querySelectorAll("#nav-container1");
        // class 값이 .nav1인 모든 요소 탐색
        const $nav1 = document.querySelectorAll(".nav1");
        // input 태그이면서 type 속성의 값이 text인 모든 요소 탐색
        const $input_text = document.querySelectorAll("input[type=text]");
        // 모든 ul 요소의 후손중에 모든 li 요소 탐색
        const $liAll = document.querySelectorAll("ul li");
        // id가 #nav-container2 첫번째 요소 탐색
        const $navContaniner2 = document.querySelector("#nav-container2");
        // $navContaniner2의 ul 태그에서 자식노드인 모든 li 요소 탐색
        const $li = $navContaniner2.querySelectorAll("ul > li");
        // class 값이 .form 첫번째 요소 탐색
        const $form = document.querySelector(".form");
        // $form의 후손중에서 div와 형제인 노드중 첫번째 span 요소 탐색
        const $span = $form.querySelectorAll("div + span");
        // $form의 후손중에서 div와 형제인 노드중 모든 span 요소 탐색
        const $spanAll = $form.querySelectorAll("div ~ span");
        // 결과 : NodeList(19) [html, head, meta, body, ...]
        console.log($all);
        // 결과 : NodeList(4) [li.nav1, li.nav2, li.nav3, li.nav4]
        console.log($liTag);
        // 결과 : NodeList [ul#nav-container1]
        console.log($navContaniner1);
        // 결과 : NodeList [li.nav1]
        console.log($nav1);
        // 결과 : NodeList(2) [input, input]
        console.log($input_text);
        // 결과 : NodeList(4) [li.nav1, li.nav2, li.nav3, li.nav4]
        console.log($liAll);
        // 결과 : NodeList(2) [li.nav3, li.nav4]
        console.log($li);
        // 결과 : <div class="form>...</div>
        console.log($form);
        // 결과 : NodeList [span.text1]
        console.log($span);
        // 결과 : NodeList(2) [span.text1, span.text2]
        console.log($spanAll);
    </script>
</html>

📃 HTMLCollection과 NodeList의 차이점은 요소를 취득하는 방법중에 NodeList로 반환하는 메소드는 querySelectorAll 밖에 없으며 차이점은 HTMLCollection은 요소 노드의 id, name 속성값으로 접근이 가능하며 Live 객체로 사용된다. 하지만 NodeList의 노드는 과거의 상태를 유지하며 Non-Live 객체이다. 하지만 Node.prototype.childNodes가 반환하는 NodeList 객체만은 Live 객체로 사용된다.

profile
JS 코린이

0개의 댓글