remove, removeChild

Creating the dots·2021년 7월 5일
0

Javascript

목록 보기
17/24

Element.remove()

Element.remove() method removes the element from the tree it belongs to.(MDN)

syntax 요소.remove()

<p id = "p1">First p</p>
<p id = "p2">Second p</p>
<p id = "p3">Third p</p>

let el = document.querySelector('#p2');
el.remove();
  • 제거된 엘리먼트는 자바스크립트 엔진의 GC(Garbage Collection)에 의해 곧 메모리에서 지워진다.

Node.removeChild(child)

The Node.removechild() method removes a child node from the DOM and returns the removed node.(MDN)

syntax 부모노드.removeChild(자식노드)

//syntax1 -Dom에서 제거되고 메모리에서도 곧 지워진다.
node.removeChild(child); 
  
//syntax2 -Dom에서 제거되지만 다시 불러올 수 있다.
let removed = node.removeChild(child);
  • child는 DOM에서 제거될 child node이고, node는 child의 parent node이다.

  • removed는 제거된 child node의 참조가 저장된다. 따라서 removed === child.

  • document.body.prepend(removed);의 형태로 다시 DOM에 붙일 수 있다.

profile
어제보다 나은 오늘을 만드는 중

0개의 댓글