0%

201228_TIL(DOM_1)

오늘 배운 것

DOM

노드

HTML을 파싱하면 결과물로 DOM이 형성된다.

요소 노드의 어트리뷰트 노드는 요소 노드와 연결되었을 뿐, 부모 노드가 없기 때문에 엄격히 말하면 DOM 트리의 구성요소가 아니라고 말할 수 있다.

요소 노드 취득

CSS 선택자를 이용한 요소 노드 취득

살아있는 객체 메서드(getElements___)는 상태를 확인하는 것이 어렵기 때문에 사용하지 않는 것이 좋다. 웬만하면 querySelector를 사용하자.

`querySelector/All``도 live 객체일 때가 있기 때문에 제일 좋은 방법은 배열로 바꿔서 사용하자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<body>
<ul>
<li id="apple">Apple</li>
<li id="banana">Banana</li>
<li id="orange">Orange</li>
</ul>
<script>
const $elem = document.querySelector("#apple");
$elem.style.color = "blue";
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<body>
<ul>
<li class="green">Apple</li>
<li class="green">Banana</li>
<li class="green">Orange</li>
</ul>
<script>
const $elems = document.querySelectorAll(".green");
$elems.forEach((elem) => {
elem.style.color = "green";
});
// [...$elems].forEach(elem => { elem.style.color = 'green'; });
</script>
</body>
</html>

HTMLCollection과 NodeList

둘 다 유사배열 객체이며 이터러블이다. 둘 다 살아있는 객체지만 NodeList는 경우에 따라 다르다(childNodes 사용 시). 때문에 가장 좋은 방법은 배열로 바꾸어 사용하는 것이다.

요소 노드의 텍스트 조작

  • nodeValue

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!DOCTYPE html>
    <html>
    <body>
    <div id="foo">Hello</div>
    </body>
    <script>
    const $foo = document.getElementById("foo");
    console.log($foo.firstChild);

    // $foo.firstChild.nodeValue = 'Foo';
    $foo.textContent = "Foo";
    </script>
    </html>

DOM 조작

  1. innerHTML

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html>
    <body>
    <div id="fruits">
    <li>Apple</li>
    </div>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");
    $fruits.innerHTML += "<li>Banana</li>";
    </script>
    </html>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <!DOCTYPE html>
    <html>
    <body>
    <div id="fruits">
    <li>Apple</li>
    <li>Grape</li>
    </div>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");
    $fruits.innerHTML = "<li>Banana</li>" + $fruits.innerHTML;
    </script>
    </html>

    하지만 위와 같이 innerHTML을 사용하며 재할당하게 되면 DOM을 다시 구성해야한다. 만약 ul안에 li가 많이 있을 경우 그 크기만큼의 DOM을 재구성하기 때문에 데이터 낭비로 직결될 수 있다.

    모던 브라우저에서는 보안 이슈(크로스 사이트 스크립팅 공격)로 innerHTML에 스크립트 태그 할당을 금지한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html>
    <body>
    <div id="foo">Hello</div>
    </body>
    <script>
    // innerHTML 프로퍼티로 스크립트 태그를 삽입하여 자바스크립트가 실행되도록 한다.
    // HTML5는 innerHTML 프로퍼티로 삽입된 script 요소 내의 자바스크립트 코드를 실행하지 않는다.
    document.getElementById('foo').innerHTML
    = '<script>alert(document.cookie)</script>';
    </script>
    </html>

    하지만 script 요소 없이도 크로스 사이트 스크립팅 공격은 가능하다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <!DOCTYPE html>
    <html>
    <body>
    <div id="foo">Hello</div>
    </body>
    <script>
    // 에러 이벤트를 강제로 발생시켜서 자바스크립트 코드가 실행되도록 한다.
    document.getElementById(
    "foo"
    ).innerHTML = `<img src="x" onerror="alert(document.cookie)">`;
    </script>
    </html>

    innerHTML을 굳이 사용하려면 HTML 새니티제이션을 같이 사용해야한다. DOMPurify.sanitize('<img src="x" onerror="alert(document.cookie)">'); // => <img src="x">

  2. insertAdjacentHTML 메서드

    Element.prototype.insertAdjacentHTML(position, DOMString) 메서드는 기존 요소를 제거하지 않으면서 위치를 지정해 새로운 요소를 삽입한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <!DOCTYPE html>
    <html>
    <body>
    <!-- beforebegin -->
    <div id="foo">
    <!-- afterbegin -->
    text
    <!-- beforeend -->
    </div>
    <!-- afterend -->
    </body>
    <script>
    const $foo = document.getElementById("foo");

    $foo.insertAdjacentHTML("beforebegin", "<p>beforebegin</p>");
    $foo.insertAdjacentHTML("afterbegin", "<p>afterbegin</p>");
    $foo.insertAdjacentHTML("beforeend", "<p>beforeend</p>");
    $foo.insertAdjacentHTML("afterend", "<p>afterend</p>");
    </script>
    </html>

    insertAdjacentHTML 메서드는 기존 요소에는 영향을 주지 않고 새롭게 삽입될 요소만을 파싱하여 자식 요소로 추가하므로 기존의 자식 노드를 모두 제거하고 다시 처음부터 새롭게 자식 노드를 생성하여 자식 요소로 추가하는 innerHTML 프로퍼티보다 효율적이고 빠르다.

  3. 노드 생성과 추가

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <!DOCTYPE html>
    <html>
    <body>
    <ul id="fruits">
    <li>Apple</li>
    </ul>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");

    // 1. 요소 노드 생성
    const $li = document.createElement("li");

    // 2. 텍스트 노드 생성
    const textNode = document.createTextNode("Banana");

    // 3. 텍스트 노드를 $li 요소 노드의 자식 노드로 추가
    $li.appendChild(textNode);

    // 4. $li 요소 노드를 #fruits 요소 노드의 마지막 자식 노드로 추가
    $fruits.appendChild($li);
    </script>
    </html>

    위 예제는 단 하나의 요소 노드를 생성하여 DOM에 한번 추가하므로 DOM은 한 번 변경된다. 이때 리플로우와 리페인트가 실행된다.

  4. 복수의 노드 생성과 추가

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <!DOCTYPE html>
    <html>
    <body>
    <ul id="fruits"></ul>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");

    ["Apple", "Banana", "Orange"].forEach((text) => {
    // 1. 요소 노드 생성
    const $li = document.createElement("li");

    // 2. 텍스트 노드 생성
    const textNode = document.createTextNode(text);

    // 3. 텍스트 노드를 $li 요소 노드의 자식 노드로 추가
    $li.appendChild(textNode);

    // 4. $li 요소 노드를 #fruits 요소 노드의 마지막 자식 노드로 추가
    $fruits.appendChild($li);
    });
    </script>
    </html>

    위 예제는 3개의 요소 노드를 생성하여 DOM에 3번 추가하므로 DOM이 3번 변경된다. 이때 리플로우와 리페인트가 3번 실행된다. DOM을 변경하는 것은 높은 비용이 드는 처리이므로 가급적 횟수를 줄이는 편이 성능에 유리하다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <!DOCTYPE html>
    <html>
    <body>
    <ul id="fruits"></ul>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");

    // 컨테이너 요소 노드 생성
    const $container = document.createElement("div");

    ["Apple", "Banana", "Orange"].forEach((text) => {
    // 1. 요소 노드 생성
    const $li = document.createElement("li");

    // 2. 텍스트 노드 생성
    const textNode = document.createTextNode(text);

    // 3. 텍스트 노드를 $li 요소 노드의 자식 노드로 추가
    $li.appendChild(textNode);

    // 4. $li 요소 노드를 컨테이너 요소의 마지막 자식 노드로 추가
    $container.appendChild($li);
    });

    // 5. 컨테이너 요소 노드를 #fruits 요소 노드의 마지막 자식 노드로 추가
    $fruits.appendChild($container);
    </script>
    </html>

    위 예제는 DOM을 한 번만 변경하므로 성능에 유리하기는 하지만 다음과 같이 불필요한 컨테이너 요소(div)가 DOM에 추가되는 부작용이 있다. 이는 바람직하지 않다.

    1
    2
    3
    4
    5
    6
    7
    <ul id="fruits">
    <div>
    <li>apple</li>
    <li>banana</li>
    <li>orange</li>
    </div>
    </ul>

    이러한 문제는 DocumentFragment 노드를 통해 해결할 수 있다. 위의 div 를 대체하는 것이다. DocumentFragment는 appendChild를 사용할 때 사라진다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <!DOCTYPE html>
    <html>
    <body>
    <ul id="fruits"></ul>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");

    // DocumentFragment 노드 생성
    const $fragment = document.createDocumentFragment();

    ["Apple", "Banana", "Orange"].forEach((text) => {
    // 1. 요소 노드 생성
    const $li = document.createElement("li");

    // 2. 텍스트 노드 생성
    const textNode = document.createTextNode(text);

    // 3. 텍스트 노드를 $li 요소 노드의 자식 노드로 추가
    $li.appendChild(textNode);

    // 4. $li 요소 노드를 DocumentFragment 노드의 마지막 자식 노드로 추가
    $fragment.appendChild($li);
    });

    // 5. DocumentFragment 노드를 #fruits 요소 노드의 마지막 자식 노드로 추가
    $fruits.appendChild($fragment);
    </script>
    </html>

노드 삽입

  1. 마지막 노드로 추가

    appendChild 사용

  2. 지정한 위치에 노드 삽입

    insertBefore 메서드는 첫 번째 인수로 전달받은 노드를 두 번째 인수로 전달받은 노드 앞에 삽입한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    <!DOCTYPE html>
    <html>
    <body>
    <ul id="fruits">
    <li>Apple</li>
    <li>Banana</li>
    </ul>
    </body>
    <script>
    const $fruits = document.getElementById("fruits");

    // 요소 노드 생성
    const $li = document.createElement("li");

    // 텍스트 노드를 $li 요소 노드의 마지막 자식 노드로 추가
    $li.appendChild(document.createTextNode("Orange"));

    // $li 요소 노드를 #fruits 요소 노드의 마지막 자식 요소 앞에 삽입
    $fruits.insertBefore($li, $fruits.lastElementChild);
    // Apple - Orange - Banana
    </script>
    </html>

노드 이동

DOM에 이미 존재하는 노드를 appendChild 또는 insertBefore 메서드를 사용하여 DOM에 다시 추가하면 현재 위치에서 노드를 제거하고 새로운 위치에 노드를 추가한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<body>
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
</body>
<script>
const $fruits = document.getElementById("fruits");

// 이미 존재하는 요소 노드를 취득
const [$apple, $banana] = $fruits.children;

// 이미 존재하는 $apple 요소 노드를 #fruits 요소 노드의 마지막 노드로 이동
$fruits.appendChild($apple); // Banana - Orange - Apple

// 이미 존재하는 $banana 요소 노드를 #fruits 요소의 마지막 자식 노드 앞으로 이동
$fruits.insertBefore($banana, $fruits.lastElementChild);
// Orange - Banana - Apple
</script>
</html>

노드 복사

Node.prototype.cloneNode([deep: true | false]) 메서드는 노드의 사본을 생성하여 반환한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<body>
<ul id="fruits">
<li>Apple</li>
</ul>
</body>
<script>
const $fruits = document.getElementById("fruits");
const $apple = $fruits.firstElementChild;

// $apple 요소를 얕은 복사하여 사본을 생성. 텍스트 노드가 없는 사본이 생성된다.
const $shallowClone = $apple.cloneNode();
// 사본 요소 노드에 텍스트 추가
$shallowClone.textContent = "Banana";
// 사본 요소 노드를 #fruits 요소 노드의 마지막 노드로 추가
$fruits.appendChild($shallowClone);

// #fruits 요소를 깊은 복사하여 모든 자손 노드가 포함된 사본을 생성
const $deepClone = $fruits.cloneNode(true);
// 사본 요소 노드를 #fruits 요소 노드의 마지막 노드로 추가
$fruits.appendChild($deepClone);
</script>
</html>

노드 교체

Node.prototype.replaceChild(newChild, oldChild) 메서드는 자신을 호출한 노드의 자식 노드를 다른 노드로 교체한다. 첫 번째 매개변수 newChild에는 교체할 새로운 노드를 인수로 전달하고, 두 번째 매개변수 oldChild에는 이미 존재하는 교체될 노드를 인수로 전달한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<body>
<ul id="fruits">
<li>Apple</li>
</ul>
</body>
<script>
const $fruits = document.getElementById("fruits");

// 기존 노드와 교체할 요소 노드를 생성
const $newChild = document.createElement("li");
$newChild.textContent = "Banana";

// #fruits 요소 노드의 첫 번째 자식 요소 노드를 $newChild 요소 노드로 교체
$fruits.replaceChild($newChild, $fruits.firstElementChild);
</script>
</html>

노드 삭제

Node.prototype.removeChild(child) 메서드는 child 매개변수에 인수로 전달한 노드를 DOM에서 삭제한다. 인수로 전달한 노드는 removeChild 메서드를 호출한 노드의 자식 노드이어야 한다. (여기서 삭제는 객체 프로퍼티 참조 값을 지우는 것을 말한다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html>
<body>
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
</ul>
</body>
<script>
const $fruits = document.getElementById("fruits");

// #fruits 요소 노드의 마지막 요소를 DOM에서 삭제
$fruits.removeChild($fruits.lastElementChild);
</script>
</html>

어트리뷰트

어트리뷰트 노드와 attributes 프로퍼티

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<body>
<input id="foo" type="text" />
</body>
<script>
console.dir(document.getElementById("foo"));
/*
attributes: NamedNodeMap
0: id
1: type
length: 2
id: id
type: type
__proto__: NamedNodeMap
autocapitalize: ""
autocomplete: ""
autofocus: false
baseURI: "http://localhost:5500/index.html"
checked: false
childElementCount: 0
*/
</script>
</html>

요소 노드의 어트리뷰트 프로퍼티를 통해 요소 속성을 조작할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html>
<body>
<input id="foo" type="text" />
</body>
<script>
const $foo = document.getElementById("foo");
// console.dir($foo.attributes.id === $foo.attributes[0]); // true

// $foo.attributes.id.value = 'bar';
// console.dir($foo.attributes.id.value); // bar

console.log($foo.getAttribute("id")); // foo
console.log($foo.getAttribute("type")); // text

$foo.setAttribute("id", "bar");
$foo.setAttribute("type", "password");

console.log($foo.getAttribute("id")); // bar
console.log($foo.getAttribute("type")); // password
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<body>
<input id="user" type="text" value="hun" />
</body>
<script>
const $input = document.getElementById("user");
console.log($input.value); // hun

$input.oninput = () => console.log($input.value);
</script>
</html>

oninput을 사용하여 console에 value 값을 실시간으로 출력할 수 있다.

Nyong’s GitHub