Home > OS >  Getting id or src on click for appended images within div
Getting id or src on click for appended images within div

Time:10-24

I am having hard time trying to get either id or src of an image that I display using the following approach.

First, I have a div element:

<div id="FeedImages"; class="imageFeed"></div>

and then I loop through images that are stored within database like this:

temp2=0;
do{                     
            var img = document.createElement("img");
            img.setAttribute("src",ImagePath);
            img.setAttribute("id",temp2);
            document.getElementById("FeedImages" i).appendChild(img);
 
temp2  ;
}while(temp<100);

This code works well in a sense that images are displayed as I wish. But I also want to have functionality where I could delete image, and for that I need to get id or src of any image. I tried just adding onclick="test(this.id)"; into div, where function would just alert clicked id, but result always comes as undefined. There surely should be same way getting out id=temp2, but I find this complicated for all the wrong reasons. Could anyone share ideas please?

CodePudding user response:

Add an onclick attribute to the img as it's created. You can pass the click event to the function that it calls and get the id from the e.target which is the click event target.

var img = document.createElement("img");
img.setAttribute("src", "https://picsum.photos/200/300");
img.setAttribute("id", "tempId");
img.setAttribute("onclick","deleteImg(event)")
document.getElementById("FeedImages").appendChild(img);

function deleteImg(e) {
  console.log(e.target.id)
  // do something with the id
}
<div id="FeedImages"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

For that you need to wrap the image and the button in one div, add a envent listner to it and remove de parent node (div).

    const ImagePath = setImageArray();
    let temp = 0;

    do {
        const div = document.createElement("div");
        const img = document.createElement("img");
        img.setAttribute("src", ImagePath[temp]);
        img.setAttribute("id", temp);
        const butn = document.createElement("button");
        butn.addEventListener('click', e => {
            e.target.parentElement.remove();
        });
        butn.innerHTML = 'X';
        div.appendChild(img);
        div.appendChild(butn);
        document.getElementById("FeedImages").appendChild(div);


        temp  ;
    } while (temp < 10);


//Setting array img source for demonstration purpose

    function setImageArray() {
        let arr = [];
        for (let i = 0; i < 10; i  ) {
            arr.push(i.toString())
        }
        return arr
    }
<div id="FeedImages" class="imageFeed"></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related