1

Assuming I have a table with column and row spans I am looking for a way to find the header that uniquely identifies a cell.

For this table:

table {
  border-collapse: collapse;
 }
 
 table, td, th {
   border: 1px solid gray;
 }
<table>
  <thead>
    <tr>
      <th colspan="2">col1</th>
      <th rowspan="2">col2</th>
      <th rowspan="3">col3</th>
    </tr>
    <tr>
      <th>col4</th>
    </tr>
    <tr>
      <th colspan="2">col5</th>
      <th>col7</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>value</td>
      <td>value1</td>
      <td>value2</td>
      <td>value3</td>
    </tr>
  </tbody>
</table>

https://jsfiddle.net/j3kqrpt0/

I would like to get the following header

col5 col5 col3 col7
Andy
  • 4,783
  • 2
  • 26
  • 51
Patrick
  • 349
  • 1
  • 7
  • 15
  • I'm not sure if I understand completely what do you wish to do. Is this desired output? https://jsfiddle.net/mn1kxp2z/ – aca Jun 24 '22 at 07:59
  • Yes that is basically what I am trying to do. – Patrick Jun 24 '22 at 08:14
  • Browsers are actually already doing this in the background, but I doubt there is an interface to access that information. What are you trying to achieve? You are not trying to replace the spanning headers by single cells, or are you? – Andy Jun 24 '22 at 08:47
  • To me it seems that the result you present in your question is not corresponding to the semantics of the used headers. This makes it impossible to provide reusable code. A single cell can have multiple headers, you can be explicit about that by means of the [`headers` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#attr-headers). If you did that, you could easily access those headers by means of javascript. – Andy Jun 24 '22 at 08:57
  • This might help: [...table header from a table cell](https://stackoverflow.com/a/46139306/2743458) – bloodyKnuckles Jun 24 '22 at 11:10

1 Answers1

0

Basically, all you have to do is -

  • Inside table, create thead element, which stands for table head
  • Create new table row - tr, which is going to be filled with column headers that you need
  • And lastly, add those th (table header) elements that you need.

Then, in the body of the table you go the same way, just with different elements:

  • Create tbody element
  • Create tr element
  • Fill tr with table data - td

Here is the code snippet.

table, th, td {
  border: 1px solid;
}
<table>
<thead>
 <tr>
   <th>col5</th>
   <th>col5</th>
   <th>col3</th>
   <th>col7</th>
 </tr>
     </thead>
      <tbody>
 <tr>
   <td>value</td>
   <td>value1</td>
   <td>value2</td>
   <td>value3</td>
 </tr>
</tbody>
</table>
aca
  • 1,071
  • 5
  • 15