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

167
Visualizações
JS - Dynamic element (button) changes the attribute's value assigned to it after creating a new dynamic element. Why?

I have a 'Save' button.

On-click 'Save' button I create a dynamic button in JS.

The name of the dynamic button is formatted by the value of a variable.

I set the new dynamic button's ID attribute to be equal to the value of the previous variable.

When I click the new dynamic button it works. It prints the value of the variable attached to it.

Problem: When I create a second dynamic button, that button also works. But the previous button does not work anymore, for some reason it prints the new value of the variable.


function saveNewProject(){
    userProject++;

    titleInputValue = document.getElementById("rightBottomContainerContentContainerContent1ElementId").value;

    newElement = document.createElement("button");

    newElement.setAttribute("type", "button");
    newElement.setAttribute("id", userProject);

    console.log(newElement);

    newElement.innerText = `${userProject} - ${titleInputValue}`;

    console.log(newElement);

    oldElement = document.getElementById("leftBottomContainerContentContainerContentElementId");

    oldElement.appendChild(newElement);

    newElementLine = document.createElement("br");
    oldElement.appendChild(newElementLine);

    console.log(newElement);

    newElement.addEventListener("click", function(){
        asd = newElement.getAttribute("id");

        console.log(asd);
        console.log(newElement);
    });
}

I am new to website development, this is my 3rd day. Thank you for your help in advance.

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

0

Use "this" inside your event handler

There is a common beginner's mistake in your code. newElement is updated each time you add a new button. And all the button event handlers use the most recent value and display the "id" of the last button added.

To make it work, you will need to change the line of code shown below. Rather than newElement, it uses "this". And within an event handler, "this" means the element to which the event is attached. So this.id returns the ID of itself rather than of the last button added.

Try the code snippet to see how it works.

// asd = newElement.getAttribute("id"); // <-- incorrect
asd = this.getAttribute("id");  // <-- correct

let userProject = 0;

function saveNewProject(){
    userProject++;

    titleInputValue = document.getElementById("rightBottomContainerContentContainerContent1ElementId").value;

    newElement = document.createElement("button");

    newElement.setAttribute("type", "button");
    newElement.setAttribute("id", userProject);

    console.log(newElement);

    newElement.innerText = `${userProject} - ${titleInputValue}`;

    //console.log(newElement);

    oldElement = document.getElementById("leftBottomContainerContentContainerContentElementId");

    oldElement.appendChild(newElement);

    newElementLine = document.createElement("br");
    oldElement.appendChild(newElementLine);

    //console.log(newElement);

    newElement.addEventListener("click", function(){
    
       
        // asd = newElement.getAttribute("id"); // <-- incorrect
        asd = this.getAttribute("id");  // <-- correct


        console.log("You clicked button " + asd);
        //console.log(newElement);
    });
}
<div id="leftBottomContainerContentContainerContentElementId" value="left">

    <input id="rightBottomContainerContentContainerContent1ElementId" value="title" />

    <button onclick="saveNewProject()">Save</button>
    
    <br/>
  
</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