thuk
thuk

Reputation: 271

how to add onclick event to create new element in 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.................

Upvotes: 7

Views: 30849

Answers (3)

Juan David Castro
Juan David Castro

Reputation: 1

For creating an attribute to a HTML tag, sometimes we have to add this:

yourTag.src
yourTag.src = 'http://lolxd.com/404.png'

But there are special attributes, and them have diferents ways for editing:

yourTag.classList
yourTag.className

And there is the onclick attribute, wichwe can use it like this:

// The first way
obj.onclick = function () { alert('lalala') }
// With the Event Listener
obj.addEventListener('click', function () { alert('lalala') }, false)
// Or, a text-render way
obj.setAttribute('onclick', 'alert(`lalala`)')

I recomend you the Event Listener way, but try all :D

Upvotes: 0

maerics
maerics

Reputation: 156394

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.

Upvotes: 18

Senad Meškin
Senad Meškin

Reputation: 13756

d.setAttribute('onclick', 'alert(\'hello\');');

Upvotes: 6

Related Questions