vic o vic vic o vic - 6 months ago 28
Javascript Question

How to get the ID of dynamically generated buttons

I auto genrated some buttons

<div class="wrapper" id="wrapper"></div>
<script type="application/javascript">
var x, i, y;
for(i = 0; i <= 10; i++){
y = i;
x = "<button class=btn_class"+y+"id=btn"+y+"onclick(alert(;>Ukor</button>";

$("button").on("click", function(){

I want to be perform different action when any of the buttons are clicked.
but i can't seem to get get the buttons by id. I also need to send y as an arguement to the function


The problem is that you have no spaces separating the attributes. So you're creating an element that looks like:

<button class=btnclass0id=btn0onclick(alert(;>Ukor</button>

So everything is going into the class attribute. You should put quotes around the attribute values, and spaces between the attributes.

There's also no need for the onclick attribute, since you're using $("button").on("click", ...) to do that.

So it should be:

x = "<button class='btn_class"+y+"' id='btn"+y+"'>Ukor</button>";

You can also use jQuery's object-oriented way to create elements:

x = $("<button>", {
        "class": "btn_class" + y,
        "id": "btn"+y,
        text: "Ukor"

BTW, why do you put y in the class? Usually the point of classes is to have all the similar elements have the same class, so you can address them all at once.