Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add onclick event to create new element in javascript

Tags:

javascript

I have created a label element. I need to add onclick event to that...

function a(me) {
    var d=document.createElement("label");
    d.id=me.id;
    d.onClick="a(10)";
    d.innerHTML="welcome";
    document.body.appendChild(d);
}

HTML:

<label id="1" onclick="a(this)">aa</label>
<label id="2" onclick="a(this)">bb</label>
<label id="3" onclick="a(this)">aa</label>

actually what happens is when i click the any of three labels in html. another label is created and displays welcome. now when i click the newly created label "welcome" it does not display anything...... that is the onclick event added to newly created label is not working ....... any suggestion.................

like image 952
thuk Avatar asked May 27 '11 18:05

thuk


1 Answers

You need to set d.onclick=function(){a(1);};, note that the case matters here (not "onClick").

[Edit]

Based on your comments and updated questions I've created a jsFiddle to demonstrate how you might turn your code into something that works.

like image 52
maerics Avatar answered Nov 12 '22 07:11

maerics