Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda