Front/JavaScript

JavaScript) DOM 조작 정리: childNodes / appendChild / removeChild / NodeList 활용

pogun 2025. 2. 24. 11:28

1. DOM (Document Object Model) 이란?

: DOM은 웹 페이지의 HTML 요소들을 객체(Object) 형태로 표현하여 JavaScript에서 조작할 수 있도록 해주는 모델

: DOM을 사용하면 HTML 태그를 추가하거나, 삭제하거나, 수정할 수 있다.

기능 전통적인 방식 최신 방식
텍스트 가져오기 element.childNodes[0].nodeValue element.textContent
선택된 값 가져오기 element.childNodes[index].text element.value
요소 추가 createElement() + appendChild() new Option() 사용 가능
요소 삭제 removeChild() remove() 사용 가능
모든 요소 가져오기 getElementsByTagName() querySelectorAll() + forEach()

2. childNodes: 노드 리스트에서 값 가져오기

: childNodes 속성을 사용하면 특정 요소의 자식 노드(Node)들을 가져올 수 있다.

<h3 id="intro">여기는 h3 태그입니다</h3>  
<button type="button" onclick="introFunc()">button</button>

<script>
function introFunc() {
    let intro = document.getElementById("intro").childNodes[0].nodeValue;
    alert(intro);
}
</script>

: childNodes[0].nodeValue를 사용하여 h3 태그 안의 텍스트 값을 가져온다.

: innerHTML을 사용하면 더 간단하게 값을 가져올 수도 있다.

편한 방법

document.querySelector("#intro").textContent;

: textContent는 innerHTML과 비슷하지만, HTML 태그를 해석하지 않고 순수한 텍스트만 반환


2-1. select 태그에서 선택된 값 가져오기

: childNodes 속성을 사용하면 <select> 태그의 옵션 값을 가져올 수 있다.

<select id="car">
    <option>벤츠</option>
    <option>BMW</option>
    <option>아우디</option>
</select>
<button type="button" onclick="choiceCar()">선택</button>

<script>
function choiceCar() {
    let name = document.getElementById("car").childNodes;
    alert(name[3].text);
}
</script>

: childNodes를 사용할 경우 텍스트 노드가 포함될 수 있어 정확한 값을 가져오기 어려울 수 있다.

: 그래서 selectedIndex 또는 value를 더 많이 사용한다.

function choiceCar() {
    let selectedCar = document.querySelector("#car").value;
    alert(selectedCar);
}

3. appendChild & insertBefore: 새로운 요소 추가하기

뒤에 요소 추가

function appendFunc(){
    let ptag = document.createElement("p");  // <p></p>
    let text = document.createTextNode("new p"); // "new p"
    
    ptag.appendChild(text);  // <p>new p</p>

    document.getElementById("demo").appendChild(ptag);
}

: appendChild()를 사용하면 특정 요소의 마지막 자식 노드로 새로운 태그를 추가할 수 있다.

 

앞에 요소 추가

function insertFunc() {
    let h3tag = document.createElement("h3");
    let text = document.createTextNode("new h3");

    h3tag.appendChild(text);
    
    let demo = document.getElementById("demo");
    let p2 = document.getElementById("p2");
    
    demo.insertBefore(h3tag, p2);  // p2 앞에 h3tag 추가
}

insertBefore()를 사용하면 특정 요소 앞에 새 요소를 삽입할 수 있다.


4. removeChild() : 특정 요소 삭제

function deleteFunc() {
    let demo = document.getElementById("demo");
    let p2 = document.getElementById("p2");

    demo.removeChild(p2);
}

5. NodeList 사용법

: getElementsByTagName()을 사용하면 특정 태그를 가진 모든 요소를 가져올 수 있다.

<p>love</p>
<p>flower</p>
<p>dream</p>

<button type="button" onclick="listFunc()">Nodelist</button>

<script>
function listFunc() {
    let nodelist = document.getElementsByTagName("p");

    nodelist[1].innerHTML = "<b>반갑</b>습니다";

    for(let i = 0; i < nodelist.length; i++){
        nodelist[i].style.backgroundColor = "#00ff00";
    }
}
</script>

5-1. forEach 사용

document.querySelectorAll("p").forEach(p => p.style.backgroundColor = "#00ff00");

: querySelectorAll()을 사용하면 더 직관적으로 모든 <p> 태그를 선택할 수 있다.


6. select 태그에 새로운 옵션 추가

: 사용자가 버튼을 클릭하면 <select> 태그에 새로운 옵션이 추가되도록 한다.

<select id="fruit">
    <option value="apple">사과</option>
    <option value="pear">배</option>
    <option value="banana">바나나</option>
</select>
<button type="button" onclick="fruitFunc()">과일추가</button>

<script>
function fruitFunc(){
    let option = document.createElement("option");
    option.innerHTML = "포도";
    option.setAttribute("value", "grape");

    let fruit = document.getElementById("fruit");
    fruit.appendChild(option);
}
</script>

6-1. new Option() 사용

function fruitFunc(){
    let option = new Option("포도", "grape");
    document.querySelector("#fruit").appendChild(option);
}

: new Option("포도", "grape")를 사용하면 더 간단하게 <option> 태그를 추가할 수 있다.