본문 바로가기
자바스크립트

[JS] 노드 생성, 추가, 삽입, 복사, 교체, 삭제

by 프로그래밍하겠습니다 2025. 2. 13.
728x90
반응형

🎶 이번 포스트에서는 자바스크립트에서 DOM에 노드를 직접 생성, 추가, 삽입, 복사, 교체, 삭제하는 방법에 대해 알아보도록 하겠다.

 

1. 노드 생성 및 추가

<!DOCTYPE html>
<html>
    <body>
        <ul id='a'>
            <li>b</li>
        </ul>
    </body>
    <script>
        const $a = document.getElementById('a');
        
        // 요소 생성
        const $li = document.createElement('li');
        
        // 텍스트노드 생성
        const textNode = document.createTextNode('c');
        
        $li.appendChild(textNode);
        $a.appendChild(li);
    </script>
</html>

 

DOM은 노드를 직접 생성/삽입/삭제/치환하는 메서드를 제공하는데, 그 종류로는 다음과 같은 것들이 있다.

  • Document.prototype.createElement(tageName) : 요소 노드를 생성하여 반환
  • Document.prototype.createTextNode(text) : 텍스트 노드를 생성하여 반환
  • Node.prototype.appendChild(childNode) : childNode에게 인수로 전달한 노드를 appendChild 메서드를 호출한 노드의 마지막 자식 노드로 추가

 

물론,텍스트 노드 생성 후 appendChild를 사용하는 방법 이외에도,  textContext 프로퍼티를 사용해 한번에 자식 노드를 추가하는 방법도 있다.

 

2. 복수 노드 생성 추가

<!DOCTYPE html>
<html>
    <body>
        <ul id='a'>
        </ul>
    </body>
    <script>
        const $a = document.getElementById('a');
        
        // 컨테이너 요소 노드 생성
        const $container = document.createElement('div');
        
        ['b','c'].forEach(text=>{
            // 요소 노드 생성
            const $li = document.createElement('li');
            
            // 텍스트 노드 생성
            const textNode = document.createTextNode('text');
            $li.appendChild(textNode);
            $container.appendChild($li);
        });
        
        $a.appendChild($container);
    </script>
</html>

 

DOM을 여러 번 변경하는 문제가 발생했을 때는, 컨테이너 요소를 사용하는 방법이 있다. 위같은 방법을 사용할 경우 DOM은 한 번만 변경되지만, 불필요한 컨테이너 요소 div가 DOM에 추가되는 부작용이 존재한다.

 

따라서, 다음과 같이 Document.prototype.createDocumentFragment 메서드를 활용하면 비어 있는 DocumentFragment 노드를 생성해 반환해준다.

<!DOCTYPE html>
<html>
    <body>
        <ul id='a'>
        </ul>
    </body>
    <script>
        const $a = document.getElementById('a');
        
        // DocumentFragment 노드 생성
        const $fragment = document.createDocumentFragment();
        
        ['b','c'].forEach(text=>{
            // 요소 노드 생성
            const $li = document.createElement('li');
            
            // 텍스트 노드 생성
            const textNode = document.createTextNode('text');
            $li.appendChild(textNode);
            $fragment.appendChild($li);
        });
        
        $a.appendChild($fragment);
    </script>
</html>

 

3. 노드 삽입/복사/교체/삭제

노드를 삽입/복사/교체/삭제 하는 메서드로는 다음과 같은 것들이 존재한다.

  • Node.prototype.appendChild : 인수로 전달받은 노드를 자신을 호출한 노드의 마지막 자식 노드로 DOM에 추가
  • Node.prototype.insertBefore(newNode, childNode) : 첫 번쨰 인수로 전달받은 노드를 두 번째 인수로 전달받은 노드 앞에 삽입
  • Node.prototype.cloneNode([deep: true or false]) : 노드의 사본을 생성하여 반환한다. deep이 true일 경우 노드를 깊은 복사하여 모든 자손 노드가 포함된 사본을 생성
  • Node.prototype.replaceChild(newChild, oldChild) : 자신을 호출한 노드의 자식 노드를 다른 노드로 교체
  • Node.prototype.removeChild(child) : child 매개변수로 전달한 노드를 DOM에서 삭제
728x90
반응형