Search code examples
javascriptjquery

How to add class to td only if text in that td and other td are present


I need to add a new class to a td (the first in the code below), but with two conditions: only if that td has a specific number on it (for example "2"), and if the next td also has some text on it (for example "6oz").

The need to add this new class, is because I will use it to count the total of units that meet the conditions mentioned above. (2 and 6oz for example)

I have a big limitation, I have several tr in the code, and I can not modify the initial code, so it won't be possible to identify the tr (in the code below).

Thanks in advance for any help!! I'll really appreciate your advice.

<tr>
  <td class="a-text-center">2</td>
  <td class="a-text-left">
      <span class="a-text-bold">bottle 6oz</span> <br>
      <div class="a-row"> 
        <span class="a-text-bold"> Condition: </span> <span> New </span> 
      </div></td>
</tr>

Solution

  • You can give the following a try, see if the following adds the class in the way you are expecting (using jQuery as mentioned in the tag):

    $(document).ready(function() {
      $('tr').each(function() {
        const firstTd = $(this).find('td:nth-child(1)');
        const secondTd = $(this).find('td:nth-child(2)');
    
        if (firstTd.length && secondTd.length) {
          const firstTdText = $.trim(firstTd.text());
          const secondTdText = $.trim(secondTd.text());
    
          if (firstTdText === '2' && secondTdText.includes('6oz')) {
            firstTd.addClass('new-class');
          }
        }
      });
    });