오늘은 DOM을 다루며 node를 생성, text 생성, 추가, 변경, 삭제, 복사 하는 방법을 정리해 보려고 한다.
저번에 올렸던 node, element - 부모 형제 자식 찾기도 궁금하다면 보러가도 좋아요. 😀
자, 첫번째는 생성부터 시작 해보자😘
이 함수는 element를 생성하는 함수이다.
<div></div>
<p></p>
와 같은 태그를 생성한다고 보면된다.
이 함수는 text node
를 생성하는 함수이다.
파라미터로 전달받은 텍스트 데이터를 텍스트 노드로 변환하여 text
를 보여준다.
const div = document.createElement('div'); // element 생성
const text = documennt.createTextNode('Hello World'); // text 생성
div.append(text); // element에 text를 추가
<div>Hello World</div>
/* 화면에는 'Hello World' 가 표출된다. */
👉🏻 다음은 생성을 했다면 내가 원하는 위치에 노드를 추가할 수 있는 함수에 대해 알아보자 !
before()
,after()
,prepend()
,append()
함수에서 파라미터로 여러 개의 노드를 넘겨주면 한꺼번에 여러개의 노드를 추가할 수 있습니다.
노드 또는 문자열을 선택된 노드의 앞에 추가
const div = document.createElement('div');
const p = document.createElement('p');
div.appendChild(p); // <div><p></p></div>
const span = document.createElement('span');
// 1.
p.before(span);
span.befor('text');
// 2.
p.before(span, 'text');
1.
<div>
text<span></span><p></p>
</div>
2.
<div>
<span></span>text<p></p>
</div>
노드 또는 문자열을 선택된 노드의 뒤에 추가
const div = document.createElement('div');
const p = document.createElement('p');
div.appendChild(p); // <div><p></p></div>
const span = document.createElement('span');
// 1.
p.before(span);
span.befor('text');
// 2.
p.before(span, 'text');
1.
<div>
<p></p><span></span>text
</div>
2.
<div>
<p></p><span></span>text
</div>
노드 또는 문자열을 선택된 노드의 첫 번째 자식 element
앞에 추가합니다.
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const two = documentn.getElementById('two');
const three = documentn.getElementById('three');
const li = document.createElement('li');
two.prepend(li); // 1.
three.prepend('text', li); // 2.
<ul id="wrap">
<li id="one"></li>
<li></li> <!-- 1. -->
<li id="two"></li>
text <!-- 2. -->
<li></li> <!-- 2. -->
<li id="three"></li>
</ul>
노드 또는 문자열을 선택된 노드의 마지막 자식 element
뒤에 추가합니다
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const two = documentn.getElementById('two');
const three = documentn.getElementById('three');
const li = document.createElement('li');
two.append(li); // 1.
three.append('text', li); // 2.
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li></li> <!-- 1. -->
<li id="three"></li>
text <!-- 2. -->
<li></li> <!-- 2. -->
</ul>
이 함수는 선택한 노드의 마지막 자식 노드 뒤에 파라미터로 전달받은 node
를 추가한다.
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const wrap = documentn.getElementById('wrap');
const li = document.createElement('li');
wrap.appendChild(li);
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
<li></li>
</ul>
이 둘은 매우 비슷 하지만 몇가지의 다른점이 있다.
append()
: node객체, text 모두 입력받는다.appendChild()
: node객체만 허용append()
: 리턴 값이 없다.appendChild()
: 추가한 자식 노드를 리턴append()
: 한번에 여러 노드를 추가appendChild()
: 오직 한번에 하나의 노드만 추가position
값beforebegin
: 부모( 선택된 )의 노드의 앞afterend
: 부모( 선택된 )의 노드의 뒤afterbegin
: 부모( 선택된 )의 첫 번째 자식의 노드 앞beforeend
: 부모( 선택된 )의 마지막 자식의 노드 뒤밑에 3가지 함수들은
before
after
append
prepend
와 비슷하지만, 다른점은position
으로 위치의 값을 지정 해 줄 수 있다는 것이다.
3가지 중 element
한가지만 예시를 만들어보았다.
insertAdjacentHTML(position, text);
이 함수는 파라미터로 받은 htmlText( HTML & XML )
를 파싱해 노드로 변환하고 이 노드를 position
으로 입력받은 위치에 추가한다.
insertAdjacentElemennt(position, element);
이 함수는 파라미터로 받은 element
를 position
으로 입력받은 위치에 추가한다.
<div id="wrap">
<h1 class="hello">Hello World!!</h1>
</div>
const wrap = document.getElementById("wrap");
const beforeBegin = document.createElement("p");
const afterBegin = document.createElement("p");
const beforeEnd = document.createElement("p");
const afterEnd = document.createElement("p");
beforeBegin.innerText = "beforeBegin";
afterBegin.innerText = "afterBegin";
beforeEnd.innerText = "beforeEnd";
afterEnd.innerText = "afterEnd";
wrap.insertAdjacentElement("beforebegin", beforeBegin);
wrap.insertAdjacentElement("afterbegin", afterBegin);
wrap.insertAdjacentElement("beforeend", beforeEnd);
wrap.insertAdjacentElement("afterend", afterEnd);
<p>beforeBegin</p>
<div id="wrap">
<p>afterBegin</p>
<h1 class="hello">Hello World!!!</h1>
<p>beforeEnd</p>
</div>
<p>afterEnd</p>
insertAdjacentText(position, text);
이 함수는 파라미터로 받은 text
를 position
으로 입력받은 위치에 추가한다.
이 함수는 newNode
를 parentNode
의 자식 노드 중 하나인 referenceNode
앞에 추가합니다.
즉, 해석하자면
새로추가할 노드를 부모노드의 자식노드 중 하나인 특정노드의 앞에 추가한다.
parentNode.insertBefore(newNode, referenceNode);
parentNode
: 기준 될 노드newNode
: 추가할 노드referentceNode
: 추가할 위치parentNode
의 자식 노드이며, newNode
는 referenceNode
의 앞에 추가null
: 부모노드의 맨 뒤에 추가childNode
: 해당 노드의 앞에 추가<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const wrap = document.getElementById('wrap');
const two = document.getElementById('two');
const firstLi = document.createElement('li');
const lastLi = document.createElement('li');
firstLi.innerText = "First li";
lastLi.innerText = "Last li";
wrap.insertBefore(firstLi, two);
wrap.insertBefore(lastLi, null);
<ul id="wrap">
<li id="one"></li>
<li>First li</li>
<li id="two"></li>
<li>Last li</li>
<li id="three"></li>
</ul>
node.replaceWith(parameter);
node.replaceWith(param1, ... , paramN);
node
를 새로운 node
( 노드 )나 String
( 문자열 )로 대체한다.
1개 이상으로도 쓸 수 있다.
<ul>
<li>First li</li>
<li id="two">center li</li>
<li>Last li</li>
</ul>
const center = document.getElementById('two'); // 기존 노드
const newCenter = document.createElement('li'); // 교체 대상 새 노드
newCenter.id = 'two';
newCenter.innerText = "new Center li";
center.replaceWith(newCenter);
<ul>
<li>First li</li>
<li id="two">new Center li</li>
<li>Last li</li>
</ul>
parentNode.replaceChild(newChild, oldChild);
부모노드의 자식노드 중 기존노드를 새 노드로 교체한다.
이 함수는 기존노드와 동일한 노드를 리턴한다.
부모노드가 기존노드의 부모노드가 아닐경우 ( 일치 하지 않을 경우 ) NotFoundError
가 발생한다.
<ul>
<li>First li</li>
<li id="two">center li</li>
<li>Last li</li>
</ul>
const center = document.getElementById('two'); // 기존 노드
const centerParent = center.parentNode; // 기존 노드의 부모 노드
const newCenter = document.createElement('li'); // 교체 대상 새 노드
newCenter.id = 'two';
newCenter.innerText = "new Center li";
centerParent.replaceChild(newCenter, center);
<ul>
<li>First li</li>
<li id="two">new Center li</li>
<li>Last li</li>
</ul>
이 함수는 선택된 노드를 삭제한다.
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const two = documentn.getElementById('two');
two.remove();
<ul id="wrap">
<li id="one"></li>
<li id="three"></li>
</ul>
이 함수는 파라미터로 전달받은 노드를 삭제한다.
❗️중요한 사실 : 파라미터로 전달한 노드는 선언한 부모의 자식노드여야한다.
여러방법으로 삭제해보자 !
<ul id="wrap">
<li id="one"></li>
<li id="two"></li>
<li id="three"></li>
</ul>
const wrap = document.getElementById('wrap');
const two = document.getElementById('two');
// 1.
wrap.removeChild(wrap.childNodes[0);
// 2.
const prent = two.parentNode;
parent.removeChild(two);
<!-- 1. -->
<ul id="wrap">
<li id="two"></li>
<li id="three"></li>
</ul>
<!-- 2. -->
<ul id="wrap">
<li id="one"></li>
<li id="three"></li>
</ul>
이 함수는 호출한 node
의 복사본을 리턴한다.
node.cloneNode(파라미터);
true
: node
의 children
까지 복사false
: 해당 node
만 복사default
값은 브라우저의 버전따라 다르기 때문에, 파라미터 값을 반드시 쓰는 것을 권장한다.<ul id="list-wrap">
<li class="list"><a>Hello</a></li>
</ul>
const listwrap = document.getElementById('list-wrap');
const list = document.querySelector('.list');
const newlist = list.cloneNode(true);
listwrap.append(newlist);
<ul id="list-wrap">
<li class="list"><a>Hello</a></li>
<li class="list"><a>Hello</a></li>
</ul>