JSFiddle - React, Tailwind, and code Playground

by Abeee Doe

HTML

<h1>Simple Table</h1>
<table id='mytable' border=1>
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
      <th>Four</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.1</td>
      <td>1.2</td>
      <td>1.3</td>
      <td>1.4</td>
    </tr>
    <tr>
      <td>2.1</td>
      <td>2.2</td>
      <td>2.3</td>
      <td>2.4</td>
    </tr>
  </tbody>
</table>

<hr>
<h1>
colSpan table
</h1>

<table id='mytable' border=1>
  <thead>
    <tr>
      <th colspan=2>One</th>
      <th>Two</th>
      <th colspan=3>Three</th>
      <th>Four</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.1.1</td>
      <td>1.1.2</td>
      <td>1.2</td>
      <td>1.3.1</td>
      <td>1.3.2</td>
      <td>1.3.3</td>
      <td>4</td>
    </tr>
    <tr>
      <td>2.1.1</td>
      <td>2.1.2</td>
      <td>2.2</td>
      <td>2.3.1</td>
      <td>2.3.2</td>
      <td>2.3.3</td>
      <td>2.4</td>
    </tr>
  </tbody>
</table>

<hr>

<h1>colSpan Table2</h1>
<table id='mytable' border=1>
  <thead>
    <tr>
      <th>One</th>
      <th>Two</th>
      <th>Three</th>
      <th>Four</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.1</td>
      <td>1.2</td>
      <td colspan="2">1.3-4</td>
    </tr>
    <tr>
      <td>2.1</td>
      <td>2.2</td>
      <td>2.3</td>
      <td>2.4</td>
    </tr>
  </tbody>
</table>
<p>
  Click on a TD to see the related header
</p>

CSS

.found {
    background-color:red!important;
}
td {
    padding:10px;
    cursor:pointer;
}
td:hover {
    background-color:grey;
}

JavaScript

function getHeadCell(td) {
  var index = Array.prototype.indexOf.call(td.parentNode.children, td);

  var table = td;
  while (table && table.tagName != 'TABLE') table = table.parentNode;

  var cx = 0;
  for (var c = 0; cx <= index; c++) cx += table.rows[0].cells[c].colSpan;

  return table.rows[0].cells[c - 1];
}




document.querySelectorAll('#mytable td')
  .forEach(e => e.addEventListener("click", function(ev) {
    var td = ev.target;

    console.log('click');
    document.querySelectorAll('td,th').forEach(el => {el.className=''});

    td.className = 'found';
    getHeadCell(td).className = 'found';

  }));