Study Record

[JavaScript] 노드를 추가/치환/삭제하기 본문

웹/Javascript

[JavaScript] 노드를 추가/치환/삭제하기

초코초코초코 2025. 4. 11. 17:50
728x90

 

 

노드 추가/치환/삭제

DOM 으로 기존의 노드에 접근하여 값을 설정하거나 취득할 수 있다. 더 나아가 문서 트리에 새 노드를 추가하거나 기존의 노드를 대체 또는 삭제할 수 있다. innerHTML 프로퍼티로도 HTML 코드를 추가할 수 있지만 좀 더 복잡한 콘텐츠를 추가할 경우를 설명하고 있다.

 

 

 신규 노드 생성하기

메소드 생성하는 노드
createElement(요소명) 요소 노드
createAttribute(속성명) 속성 노드
createTextNode(텍스트) 텍스트 노드
createCDATASection(텍스트) CDATA 섹션
createComment(텍스트) 주석 노드
createEntityReference(실체명) 실제 참조 노드
createProcessingInstruction(타깃명, 데이터) 처리 명령 노드
createDocumentFragment() 문서의 단편

 

예시)

// <a href="http://www.naver.com">네이버</a>
function createListNode() {
    var a = document.createElement('a');
    a.setAttribute('href', 'http://www.naver.com');
    a.appendChild(document.createTextNode("네이버"));

    document.querySelector('body').appendChild(a);
}

 

+ 속성 추가하기

function createListNode() {
    var a = document.createElement('a');
    
    var attri = document.createAttribute('target');
    var attri2 = document.createAttribute('href');
    
    attri.value = "_blank";
    attri2.value = "http://www.naver.com";

    a.setAttributeNode(attri);
    a.setAttributeNode(attri2);

    a.appendChild(document.createTextNode("네이버"));
    document.querySelector('body').appendChild(a);
}

 

 

 노드끼리 조립하기

노드를 생성했으면 노드를 조합하는 것으로 문서에 추가하는 작업이 가능하다.

 

① appendChild 메소드

appendChild 메소드는 추가된 순서대로 제일 마지막 자식 요소로서 지정된 요소를 추가한다. 다음 예시는 <body> 태그 맨 마지막 자식 요소로 a 노드가 추가된다.

document.querySelector('body').appendChild(a);

 

② insertBefore 메소드

insertBefore(n1, n2) 메소드는 n2 앞에 n1 노드를 배치한다. 

 

예시) parent-btn 요소 앞에 br 태그 배치

var br = document.createElement('br');
var btn = document.getElementById('parent-btn');
document.querySelector('body').insertBefore(br, btn);

 

예시) body 태그의 마지막 자식 요소로 p 태그 배치

var p = document.createElement('p');
p.textContent = "HEllo";
document.querySelector('body').insertBefore(p, null);

 

예시) body 태그의 첫번째 자식 요소로 p 태그 배치

var body = document.querySelector('body');
var p = document.createElement('p');
p.textContent = "HEllo";

body.insertBefore(p, body.firstChild);

 

 

 복잡한 콘텐츠를 작성하는 경우 - DocumentFragment 객체

복잡한 콘텐츠를 작성하는 경우 DOM 문서에 appendChild 함수를 호출하여 노드를 추가하는 것은 가벼운 작업이 아니기 때문에 자제하는 것이 좋다. 이 때, DocumentFragment 객체에 콘텐츠를 조립한 후 함께 문서 트리에 추가하는 방법이 바람직하다. DocumentFragment 객체는 문서의 조각이며, 조립한 노드를 일시적으로 보관하기 위한 그릇이다.

 

예시) <ul id="list"> 태그에 목록(li)태그 생성하기

// 페이지 로드시 실행되는 이벤트 리스너를 등록한다.
document.addEventListener('DOMContentLoaded', function() {
    
    createListNode(['치킨', '만두', '라면', '디저트', '커피']);

}, false);

function createListNode(listValue) {
    var frag = document.createDocumentFragment();

    for(var i=0; i<listValue.length; i++) {
        var element = document.createElement('li');

        element.textContent = listValue[i];

        frag.appendChild(element);
    }

    document.getElementById('list').appendChild(frag);
}

 

 

 노드 치환하기

자식 노드를 치환하는 것은 replaceChild 메소드의 역할이다. 두번째 인수의 노드를 첫번째 인수의 노드로 바꾼다.

// 페이지 로드시 실행되는 이벤트 리스너를 등록한다.
document.addEventListener('DOMContentLoaded', function() {
    
    var parent = document.getElementById('bin-ex');
    var after = createNode();

    parent.replaceChild(after, parent.firstChild);
}, false);

 

 

 노드 삭제하기

자식 노드를 삭제하는 것은 removeChild 메소드의 역할이다. 인수로 삭제 대상의 노드 값이 들어간다. 

var parent = document.getElementById('bin-ex');
parent.removeChild(parent.firstChild);

 

728x90