jqueryjquery-selectorssiblings

jQuery: add class to sibling rows columns of same index


I've created function to find columns which contains number, then add class to them and to the next columns before code find an empty column. I also want to add class to the columns below (next rows but columns of same index) but I can't solve it. I've tried .parent() method but I'm stuck and I don't know what i'm doing to be honest... Here's my code

  $("table tbody tr td").each(function () {
    var num = $(this).text();
    if ($.isNumeric(num)) {
      $(this).addClass('word-' + num).nextUntil('td:empty').addClass('column-' + num);
    }
  });

And here's image to show what i want to do (red fields).enter image description here

Sorry for my english.


Solution

  • Within your if statement, you could add something along the lines of:

    JS Fiddle

    var indexed = $(this).index() + 1; // Get column number
    var row = $('tr').has(this); // Current row
    row.nextAll('tr').each(function(e) {
      var cell = $(this).find('td:nth-child(' + indexed + ')');
    
      if(cell.text().length) {
          cell.addClass('word-' + num);
      } else {
          return false; // End loop if word is finished
      }
    
    });
    

    Bonus

    If you want to style where words intersect (have two classes attached that start with "word-", you could do something like:

    /* Intersection */
    [class^='word-'][class*=' word-'] {
      font-weight: bold;
      background: grey;
      color: white;
    }