[JavaScript] DOM 노드 생성, 추가, 복제, 삭제 ✅

parkheeddong·2023년 5월 12일

JavaScript

목록 보기
17/26
post-thumbnail

✨ 노드 종류와 노드 값 보기 : nodeName, nodeValue

<!DOCTYPE html>
<html>
<head>
    <meta charset = 'UTF-8' />
</head>
<body>
    <h1> Welcome </h1>
    <h2> World </h2>
    <ul id = 'color' >
        <li id = 'red'>  red </li>
        <li id = 'blue'> blue </li>
        <li id = 'yellow'>  yellow </li>
    </ul>
</body>
</html>
const blue = document.getElementById('blue');
blue.firstChild;
// ➡ blue의 자식노드는 text노드("blue") 이다.
blue.firstElementChild;
// ➡ null이다. 자식 요소 노드는 없기 때문이다..!

const blueTextNode = blue.firstChild;

blueTextNode.nodeName;
'#text' : text 노드이다.

blueTextNode.nodeValue;
' blue ' 가 노드의 value이다.



✨ 노드 수정 : nodeValue, innerHTML

1) nodeValue를 이용하여 텍스트 노드의 value를 수정할 수 있다.

nodeValue는 모든 노드가 가진 프로퍼티이지만 텍스트 노드가 아니면 null을 반환하기 때문에, 텍스트노드에서만 nodeValue를 이용해 수정 가능하다.

blueTextNode.nodeValue = '파랑'; // 변경

const ul = document.getElementById('color');

ul.nodeType; // 1  -> 노드타입1은 요소 노드..! 
ul.nodeName; // 'UL' -> 노드 네임 (요소노드의 태그명)
ul.nodeValue; // null -> 텍스트 노드에서만 nodeValue를 이용해 텍스트를 수정할 수 있다.

2) innterHTML 사용하여 node의 value를 수정할 수 있다.

innerHTML의 단점은 요소를 추가, 제거, 수정할 때마다 다시 모든 html을 string으로 작성해야 한다는 점이다.

ul.innerHTML = '<li> RED <li>' // '<li> RED <li>'
ul.innerHTML = '<li>RED<li><li>BLUE<li>'
// <li> RED <li> 밑에 blue를 추가하려면 이와 같이 해야 하므로 불편하다..!


✨ 노드 생성 : createElement

const newLi = document.createElement('li'); 
newLi; // <li></li>
newLi.innerHTML = 'Green'; // 'Green'


✨ 부모의 자식노드로 추가 : appendChild, insertBefore

1) appendChild는 가장 마지막 자식 노드로 추가한다.

const newLi = document.createElement('li'); 
newLi; // <li></li>
newLi.innerHTML = 'Green'; // 'Green'
ul.appendChild(newLi); // <li>…</li>

innerHTML 대신 createTextNode를 이용할 수도 있다.

const newLi = document.createElement('li');
const newText = document.createTextNode('pink'); 
newText; // "pink"
newLi2.appendChild(newText); // "pink"
ul.appendChild(newLi2); // <li>…</li>

2) 위치를 특정 노드 전에 추가하려면 insertBefore를 이용한다.

const newLi = document.createElement('li');
const textNode = document.createTextNode('black');
newLi.appendChild(textNode3); //"black"
const red = document.getElementById('red'); 
ul.insertBefore(newLi3, red); // <li>…</li> -> red 노드 전에 추가된다


✨ 노드 복제 : cloneNode

cloneNode에 인수로 true를 복잡하면 자식노드까지 복사되지만
false나 아무것도 전달하지 않으면 자식노드는 복사되지 않는다.

const newBlack = newLi3.cloneNode();
newBlack; // <li></li>
const newBlack2 = newLi3.cloneNode(true);
newBlack2; // <li>black</li>


✨ 노드 삭제 : removeChild

ul.removeChild(red); // ul의 자식 노드 삭제된다
ul.removeChild(ul.firstElementChild); // 첫 자식요소노드 삭제
ul.removeChild(ul.lastElementChild); // 마지막 자식요소노드 삭제

0개의 댓글