How to add onclick event to create a new element in javascript

I created a label element. I need to add an onclick event to this ...

 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 when I click on any of the three tags in html. a shortcut is created and displayed. Now, when I click on the newly created shortcut "welcome", it does not display anything ...... that is, the onclick event added to the newly created shortcut does not work ....... any suggestion ...... ...........

+7
source share
3 answers

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

[change]

Based on your comments and updated questions, I created jsFiddle to demonstrate how you can turn your code into something that works.

+17
source
 d.setAttribute('onclick', 'alert(\'hello\');'); 
+6
source

To create an attribute for an HTML tag, sometimes we need to add this:

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

But there are special attributes, and they have different editing methods:

 yourTag.classList yourTag.className 

And there is an onclick attribute that 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 recommend you a way to listen to events, but try everything: D

0
source

All Articles