HTML DOM Elements (Nodes)

박종한·2020년 3월 10일
0

DOM

목록 보기
10/12

새로운 HTML 요소(노드) 생성(createElement())

HTML DOM에 새로운 요소를 추가하기 위해서, 요소(요소 노드) 생성을 먼저해주고, 그 다음에 기존에 존재하는 요소에 그것을 적용합니다.

<div id="div1">
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var element = document.getElementById("div1");
element.appendChild(para);
</script>

먼저, para를 통해 새로운 <p> HTML 요소를 만들어냅니다.
그 후, 안에 들어갈 텍스트 노드를 생성하고, 그것을 para에 적용시킵니다.
(<p>요소 안에 문자를 넣기 위해서는, 텍스트 노드를 생성하는 것이 필수입니다.)
그 후, para역시 기존의 <div id="div1">에 적용시킵니다.

insertBefore()

하지만 위 방법을 사용하면, 무조건 새롭게 추가한 요소가 항상 마지막에 추가되는데요.
insertBefore()이 그 점을 해결해줍니다. 삽입하고자 하는 요소를 앞에 찍고
element.insertBefore(para, old) 이런식으로 element요소안에 새롭게 추가할 para를 기존의 요소 old앞에 넣어줍니다.

기존하는 HTML 요소 삭제(remove())

<div>
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
var elmnt = document.getElementById("p1");
elmnt.remove();
</script>

기존하는 p1아이디를 가지는 HTML 요소를 HTML DOM을 통해 가져오고, .remove()만 해주면 됩니다.

removeChild()

문제는 오래된 브라우저에선 remove()를 지원하지 않습니다.
그럴땐 부모요소.removeChild(자식)을 사용해야 합니다.

<div id="div1">
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>

기존에는 그냥 p1을 아이디로 하는 요소를 가져와서 바로 remove해줬는데, 오래된 브라우저는 꼭 부모 요소도 같이 HTML DOM을 통해 가져와서 부모를 통해 자식을 지워줘야 합니다.

HTML 요소 대체하기(replaceChild())

<div id="div1">
  <p id="p1">This is a paragraph.</p>
  <p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);

var parent = document.getElementById("div1");
var child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>

para를 통해 새로운 요소를 만들고, 그 안의 내용물을 node를 통해 텍스트 노드로 채워줍니다.

그 후 부모 요소와, 대체할 자식 요소를 불러오고
부모요소.replaceChild(대체할 자식, 대체될 자식) 으로 해주면 됩니다.

profile
코딩의 고수가 되고 싶은 종한이

0개의 댓글