1

I'm using this code snippet from W3Schools to create a new row in my table:

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";

After creating it, all the rows in the table have their onClick functions except the one I just created, so my question is, how can I specify an onClick function for that row?

2 Answers 2

2

you can also use

document.getElementById("myTable").innerHTML+="<tr onClick='myFunc();'></tr>"

or by your way you can use

row.onClick="myFunc();"   

or

 row.setAttribute( "onClick", "javascript: myFunc();" )
Sign up to request clarification or add additional context in comments.

2 Comments

Couldn't get the first or second version to work, but the third one seemed to solve my problem. Thank you!
actually that was by mistake i write the cell1 in place of row
1

Or add this event listener later:

var obj=document.getElementsByTagName("tr")[0]
obj.onclick=function(){alert("whatever")};

where [0] 0= row number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.