반응형

Node.appendChild()

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position.

 

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

 

Node.appendChild() - Web APIs | MDN

The appendChild() method of the Node interface adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new pos

developer.mozilla.org

 

appendChild로 현재 돔에 위치한 태그를 파라미터로 줄 경우

파라미터로 들어간 태그가 appendChild를 받는 부모 태그의 자식 태그로 이동하는 효과가 있다.

이를 이용해서 쉽게 drag event를 만들 수 있다.

 

const draggables = document.querySelectorAll(".draggable");
const containers = document.querySelectorAll(".container");
const test = document.querySelector(".draggable");

console.log(test);
console.log(containers[1].appendChild(test));
console.log(draggables);
draggables.forEach((draggable) => {
  draggable.addEventListener("dragstart", () => {
    draggable.classList.add("dragging");
  });

  draggable.addEventListener("dragend", () => {
    draggable.classList.remove("dragging");
  });
});

containers.forEach((container) => {
  container.addEventListener("dragover", () => {
    console.log("drag over");
    const draggable = document.querySelector(".dragging");
    console.log(draggable);
    container.appendChild(draggable);
  });
});

+ Recent posts