상현에 하루하루
개발자의 하루

prependChild() 구현

( 업데이트: )

Node.appendChild()를 사용해서 해당 노드에 대해서 맨마지막에 Node를 넣을 수 있다. 그렇다면 어떻게 첫번째 자식으로 추가할 수 있을까?

단순하게 생각하면 prependChild()로 생각할 수 있지만 prependChild()는 존재하지 않는다.

Element.prototype.prepend

Node.prototype에서가아닌 Element.prototype에서 prepend()기능을 이용해서 필자가 생각했던 대로 동일하게 기능이 작동한다.

Node.appendChild()Element.append()의 차이점과 동일하게

  • 반환값이 없다
Node.prototype.prependChild = Element.prototype.prepend

위와 같이해서 사용해도 괜찮다.

비슷한 다른 구현

그래서 insertBefore()firstChild를 사용해서 동일하게 구현할 수 있다.

const targetNode = document.querySelector('#targetNode');
const selectNode = document.querySelector('#selectNode');
targetNode.insertBefore(selectNode, targetNode.firstChild);Code language: JavaScript (javascript)

위처럼 targetNode에 첫번째 자식으로 selectNode를 추가할 수 있다.