1

I have the following code which represents an HTML Table and after button onClick I create one more same HTML Table.

The problem is that the second table is not listening on the Function applied to the first table as well that highlights the cells.

I am trying to figure out if there is something that preventing the second table to listen to the script code as well.

Any ideas would be much appreciated.

The style CSS is :

         table,tr,th{
         border:2px solid black;
         }
         table{
         width:200px;
           height:200px;
         }
         th.highlight {
         background-color: black;
          } 

The HTML Table looks like this :

         <table id="test">
         <tr><th>test</th><th>test</th><th>test</th></tr>
         <tr><th>test</th><th>test</th><th>test</th></tr>
         <tr><th>test</th><th>test</th><th>test</th></tr>

         </table>
         <div id="test2">

         </div>
         <button type="button">Add</button>
        

And the Script that applies to the first table but it is not working on the second :

    const addColumn = () => {
    var x = document.getElementById("test2");
    x.innerHTML = "<table> <tr><th>test2</th><th>test2</th><th>test2</th></tr> <tr> 
    <th>test2</th><th>test2</th><th>test2</th></tr> <tr><th>test2</th><th>test2</th> 
    <th>test2</th></tr></table>";
    }

    document.querySelector('button').onclick = addColumn
    $('th').hover(function() {
     $(this).addClass('highlight');
     
 }, function() {
     $(this).removeClass('highlight');
 
 });
Zoe
  • 27,060
  • 21
  • 118
  • 148
Gial Jim
  • 33
  • 5
  • To have event handlers bind to dynamic content you need to delegate them. See the duplicate for how to do that. – Rory McCrossan Jun 29 '22 at 09:07
  • A better way to accomplish the highlighting would be with the CSS [:hover](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover) pseudo-class. Run this [snippet](https://jsfiddle.net/kwy60uve/) to see it in action. – Lonnie Best Jun 29 '22 at 10:43
  • @ZoestandswithUkraine : I'll indeed refrain from abusing edits to bypass closure. I wish, however, that there was some way to contest premature closure. The fact that Rory himself posted an answer outside of stackoverflow (after closing the question) is a strong testimony that he should have instead reopened the question to allow a variety of solutions to the problem (instead of prematurely forcing one solution with closure). See my comment above. It is a totally different solution, but due to premature closure I've had to post my snippet outside of stackoverflow. Shouldn't that be an answer? – Lonnie Best Jun 29 '22 at 11:00
  • @LonnieBest you're correct - the CSS solution was not covered in the answer that I marked as a duplicate. To rectify this I added another duplicate which does cover that case. – Rory McCrossan Jun 29 '22 at 11:07

0 Answers0