I am trying to dynamically add input file images to separate divs on an HTML page without using get element by class name. Each div should have a unique image associated with it instead of adding the same image to all divs with the same class. Can anyone provide some guidance or assistance with this? Thank you.
Currently, the code I have adds the same image to all divs with the specified class, but I need each div to have its own exclusive image.
Additional information: I am creating a new div each time and I want to assign a distinct image to each div that I create.
Below is the complete code for creating a new div and adding a picture:
mainspan.onclick = () => { // mainspan is button used to create div
let div = document.createElement("div");
div.classList.add("main-dd"); let button = document.createElement("button"); let img = document.createElement("img"); img.classList.add("currentimg");
div.appendChild(img); button.classList.add("btnaddinfo");
button.innerHTML = "Add item"; button.addEventListener("click", () => { addinfo.style.display = "block"; // the menu to add the new picture }); div.appendChild(button);const uploadPictureButton = document.querySelector(".photo-upload");
uploadPictureButton.addEventListener("change", function () { displayPicture(this); });
function displayPicture(input) { if (input.files && input.files[0]) { var reader = new FileReader();
reader.onload = function (e) { document .querySelector(".currentimg") .setAttribute("src", e.target.result); }; reader.readAsDataURL(input.files[0]); } } }; })
document.querySelector(".photo-upload"); uploadPictureButton.addEventListener("change", function () { displayPicture(this); }); let a; function displayPicture(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { document .querySelector(".currentimg") .setAttribute("src", e.target.result); }; reader.readAsDataURL(input.files[0]); } }