holian
holian

Reputation: 755

How to add event attribute to html tag with JavaScript

I created some label tag with JavaScript something like this:

 var labelTag = document.createElement("label"); 
 labelTag.id = i; 
 labelTag.className ="myrows"; 
 labelTag.innerHTML = data[1];

It's ok, but I need to add onlick attribute to this label too.

So I need to look the result something like this:

  <label id='0' class='myrows' onclick=myfunction('first','second',..)> some info here</label>

I try with this: labelTag.onclick=myfunction('first',second,...);

No code error, but after I run the page on browser and see the source this attribute is missing. What's wrong?

Upvotes: 0

Views: 3347

Answers (2)

Pav
Pav

Reputation: 2328

var labelTag = document.createElement("label"); 
labelTag.id = i; 
labelTag.className ="myrows"; 
labelTag.innerHTML = data[1];
labelTag.onclick = function() {
   alert('Clicked');
};

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816552

This

labelTag.onclick = myfunction('first', 'second', ...);

assigns the return value of myfunction to labelTag.onclick.

You have to wrap it into an anonymous function if you want to pass parameters to the function:

labelTag.onclick = function() {
    myfunction('first', 'second', ...);
};

Note that you won't see any changes in the DOM if you inspect it.


For more information about event handling and the various ways to attach handlers, I recommend to read the excellent articles on quirksmode.org.

Upvotes: 3

Related Questions