# Javascript: assign event listeners to elements dynamically added in a loop

**URL:** <https://forum.kirupa.com/t/javascript-assign-event-listeners-to-elements-dynamically-added-in-a-loop/327353>\
**Category:** Uncategorized\
**Created:** [February 23, 2012, 3:28pm UTC](https://forum.kirupa.com/t/javascript-assign-event-listeners-to-elements-dynamically-added-in-a-loop/327353 "2012-02-23T15:28:51Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![natronp](https://avatars.discourse-cdn.com/v4/letter/n/87869e/32.png) [@natronp](https://forum.kirupa.com/u/natronp)\
**Post date:** [February 23, 2012, 3:28pm UTC](https://forum.kirupa.com/t/javascript-assign-event-listeners-to-elements-dynamically-added-in-a-loop/327353/1 "2012-02-23T15:28:51Z")

</div>

I’m having trouble figuring out how to assign event listeners to html elements i’m dynamically creating in a loop within my javascript function.

My code works but only the last element added has the listener assigned and does what it should when clicked.

My ‘code’ variable is being properly assigned (to the last dynamically added element only of course), so it must have something to do with how i’m assigning the listener…?

code:

```auto
function updateDisplay(){
var cartDiv = document.getElementById('cartContents');
cartDiv.innerHTML = "";

if(myCart.length > 0)
{
for(i=0; i<=myCart.length; i++)
{
var iCode = myCart*.code;

cartDiv.innerHTML += "<div class='cartItem'><strong>"+iCode+"</strong><br/> "+myCart*.name+"<div class='cartItemQty'>"+myCart*.qty+"</div><div id='"+iCode+"'></div><img src='images/design/oneGray.gif' width='260' height='1'/></div><br/>";

var trgDiv = document.getElementById(iCode);
this["removeBtn"+i] = document.createElement("button");
this["removeBtn"+i].innerHTML = "remove";
this["removeBtn"+i].code = iCode;

this["removeBtn"+i].addEventListener("click", function(){ removeFromCart(this.code);}, false);
trgDiv.appendChild(this["removeBtn"+i]);

}
cartDiv.innerHTML += "<br/><div class='cartBtn'><button border='0' onClick='placeOrder()' style='width: 91px; height: 27px;'>place order</button></div>";
}else{
//array has no items
cartDiv.innerHTML = "cart empty - add items";
}

}

```
