简体   繁体   中英

How do you append an element created by a for loop to an existing div?

I am attempting to drag and drop an image created by a for loop from one div (called here sideDiv) to another (called dropZone here). With the current code I have I am getting an Uncaught DOMException: Failed to execute 'append' on 'Element': The new child element contains the parent and am a bit lost as to why I am getting this. I am a JavaScript noobie and have done a bit of googling and haven't come up much with an answer as to how I can solve this. I have seen videos of where the element that is appended is appended by using a variable that is stored globally, however since these images are generated by a for loop in a function I don't seem to be able to access them. Any help with this would be greatly appreciated. Attached is the relevant Javascript.

JS fiddle here: https://jsfiddle.net/h9e6034s/



const dropZone = document.getElementById("dropZone");

console.log(dropZone);

let sideDiv = document.getElementsByClassName("pizzaIngredients")[0];

const dragStart = () => {
  console.log("start");
};

const dragEnd = () => {
  console.log("end");
};

const dragOver = (e) => {
  e.preventDefault(); //necessary for the drop, otherwise drop doesn't run
  console.log("over");
};

const dragEnter = (e) => {
  e.preventDefault();
  console.log("enter");
};

const dragLeave = () => {
  console.log("leave");
};

const dragDrop = (e) => {
  dropZone.append(e.target);
  console.log("dropped");
};

//drop zone event listeners
dropZone.addEventListener("dragover", dragOver);
dropZone.addEventListener("dragenter", dragEnter);
dropZone.addEventListener("dragleave", dragLeave);
dropZone.addEventListener("drop", dragDrop);

//creating pictures

const createPictures = () => {
  for (let i = 1; i < 10; i++) {
    let newImage = document.createElement("img");
    newImage.setAttribute("src", "images/" + [i] + ".jpg", newImage);
    newImage.classList.add("toppings");
    newImage.setAttribute("draggable", "true");
    newImage.addEventListener("dragstart", () => {
      newImage.classList.add("dragging");
      dragStart();
    });
    newImage.addEventListener("dragend", () => {
      newImage.classList.remove("dragging");
      dragEnd();
    });
    sideDiv.appendChild(newImage);
  }
};

createPictures();

One way to make it work is to set a variable when the start drag begins, then access that on drop

let curEl

...

const dragDrop = (e) => {
  dropZone.append(curEl);
  console.log("dropped");
};

...
 newImage.addEventListener("dragstart", () => {
      newImage.classList.add("dragging");
       curEl=newImage
      dragStart();
    });

....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM