Uncaught DOMException: Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node

Viewed 90

User should be able to drag and drop image and the only condition is images should be replaced by their position, is their any otherway I can achieve the same like without using setdata and getdata .

let dragindex = 0;
let dropindex = 0;
let clone = "";

function drag(e) {
  e.dataTransfer.setData("src", e.target.id);
  console.log(e.target.id);
}

function drop(e) {
  e.preventDefault();
  clone = e.target.cloneNode(true);
  let data = e.dataTransfer.getData("src");

  let nodelist = document.getElementById("imageListId").childNodes;
  console.log(nodelist);
  for (let i = 0; i < nodelist.length; i++) {
    console.log(nodelist[i]);
    if (nodelist[i].id == data) {
      dragindex = i;
    }
  }
  
  console.log(document.getElementById(data));
  console.log(e.target);
  document.getElementById("imageListId").replaceChild(document.getElementById(data), e.target);

  document.getElementById("imageListId").insertBefore(clone, document.getElementById("imageListId").childNodes[dragindex]);
}

function allowDrop(e) {
  e.preventDefault();
}
body {
  text-align: center;
}

/* image dimension */
img {
  height: 200px;
  width: 350px;
}

/* imagelistId styling */
#imageListId {
  margin: 0;
  padding: 0;
  list-style-type: none;
}

#imageListId div {
  margin: 0 4px 4px 4px;
  padding: 0.4em;
  display: inline-block;
}

/* Output order styling */
.listitemClass {
  border: 1px solid #006400;
  width: 350px;
}

.height {
  height: 10px;
}
<div class="height"></div><br>

<div id="imageListId">
  <div id="div1" class="listitemClass" ondrop="drop(event)" ondragover="allowDrop(event)">
    <img id="drag1" draggable="true" ondragstart="drag(event)" src="https://images.fastcompany.net/image/upload/w_1280,f_auto,q_auto,fl_lossy/w_596,c_limit,q_auto:best,f_auto/fc/3034007-inline-i-applelogo.jpg" alt="">
  </div>

  <div id="div2" class="listitemClass" ondrop="drop(event)" ondragover="allowDrop(event)">
    <img id="drag2" draggable="true" ondragstart="drag(event)" src="https://www.tailorbrands.com/wp-content/uploads/2020/07/mcdonalds-logo.jpg" alt="">
  </div>

  <div id="div3" class="listitemClass" ondrop="drop(event)" ondragover="allowDrop(event)">
    <img id="drag3" draggable="true" ondragstart="drag(event)" src="https://cdn.dribbble.com/users/24078/screenshots/15522433/media/e92e58ec9d338a234945ae3d3ffd5be3.jpg?compress=1&resize=400x300" alt="">
  </div>
</div>

I am trying to drag and drop the images into different divs and the dropable div's image should be replaced by the drag image position should I be using divs as draggable and image as droppable or drag drop should only be at my divs Thankyou for answers in advance.

0 Answers
Related