Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding onclick event to newly created table header in javascript, but the onclick function is added to all th's on the page, not just the one I want
    text
    copied!<p>I'm generating a table in js and using a function as follows for some of the headers:</p> <pre><code>function generateTableHeader(table) { var tr = document.createElement('tr'); var th = document.createElement('th'); th.onclick = function(){ toggleHidden("hide_header_" + table_count); }; th.appendChild(document.createTextNode(key)); tr.appendChild(th); table.appendChild(tr); } </code></pre> <p>My toggle hidden function just hides all elements of the class "hide_header_{some number}". It works fine.</p> <p>The problem is, I call this generateTableHeader function several times, creating headers for multiple tables - each time it's called table_count (global variable) is incremented and I expected this function to hide only the class of elements with the number it has when the onclick event is created. Instead, whenever I click on any of the headers, they always hide the last element created.</p> <p>The function is called 4 times to create 4 table headers in 4 different tables - each has a column of td's with the correct class name (i.e. "hide_header_1", "hide_header_2" and so on). When I click on the first header, the fourth table column is hidden/show. When I click the second, third, or fourth, still only the fourth column is hidden/show. I want each th click to hide only the td's in that table.</p> <p>It's as if the th onclick event I am creating is being overwritten each time I call this function, not sure why. Any ideas?</p> <p>Any help would be appreciated!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload