Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
Getting id or src on click for appended images within div

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda