JSFiddle - React, Tailwind, and code Playground

Table index functions: getNonColSpanIndex() getCellAtNonColSpanIndex(index) See also http://stackoverflow.com/q/1166452/490560

by Ignitor

HTML

<table>
  <tbody>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
    <tr>
      <td colspan="2">One</td>
      <td colspan="2">Two</td>
      <td colspan="2">Three</td>
    </tr>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
  </tbody>
</table>

<div>
    <p>Click on a cell to see it's "NonColSpanIndex": <span id="nonColSpanIndex"></span></p>
    <label for="nonColSpanSelect">Select cells with nonColSpanIndex:</label> <input type="number" id="nonColSpanSelect"/>
</div>

CSS

table, th, td {
    border: 1px solid black;
    padding: 3px;
}

.selected {
    border: 1px solid red;
}

JavaScript

$.fn.getNonColSpanIndex = function() {
    if(! $(this).is('td') && ! $(this).is('th'))
        return -1;

    var allCells = this.parent('tr').children();
    var normalIndex = allCells.index(this);
    var nonColSpanIndex = 0;

    allCells.each(function(i, item) {
        if(i == normalIndex)
            return false;

        var colspan = $(this).attr('colspan');
        colspan = colspan ? parseInt(colspan) : 1;
        nonColSpanIndex += colspan;
    });

    return nonColSpanIndex;
};
$.fn.getCellAtNonColSpanIndex = function(index) {
    if (index < 0)
        return $();
    
    var $result = $();
    $(this).each(function(i, element) {
        var $ele = $(element);
        if(! $ele.is('tr'))
            return true;
        
        var allCells = $ele.children();
        var nonColSpanIndex = -1;
        var $cell = $();
            
        allCells.each(function(i, item) {
            var colspan = $(item).attr('colspan');
            colspan = colspan ? parseInt(colspan) : 1;
            nonColSpanIndex += colspan;

            if (nonColSpanIndex >= index) {
                $cell = $(item);
                return false;
            }
        });
        
        $result = $result.add($cell);
    });
    
    return $result;
};

$(document).ready(function() {
    $('table td,table th').on('click', function() {
        $('#nonColSpanIndex').text($(this).getNonColSpanIndex());
    });
    $('#nonColSpanSelect').on('change', function() {
        var nonColSpanIndex = parseInt($(this).val());
        $('.selected').removeClass('selected');
        $('table tr').getCellAtNonColSpanIndex(nonColSpanIndex).addClass('selected');
    });
});