0

Hello I am trying to loop through a table I have in html and want to add next to the cell depending on the value of the cell. For example the following table I have:

<div>
   <h1>My Table</h1>
   <table id = "table" class = "searchable sortable">
      <tr class = "header">
          <th>A</th>
          <th>B</th>
          <th>C</th>
     </tr>
     <tr>
          <td> Up</td>
          <td>Down</td>
          <td> Up </td>
     </tr>
     <tr>
          <td>Up</td>
          <td>Up</td>
          <td>Down</td>
    </tr>
  </table>
<div>

if the value of the cell is equal to up I would like to add a image in the cell of an up arrow, if down add a image of a down arrow.

  • Welcome to Stack Overflow! Questions asked here must include the solution attempted by the asker. You should attempt this yourself first, and if you run into any problems, show us what you did and we will be more than glad to help. Refer to the [help center](https://stackoverflow.com/help). – Wais Kamal Dec 19 '20 at 09:28
  • @WaisKamal Thank you, I should give this a run for a few days and follow up on my findings. – duektime201823 Dec 19 '20 at 09:31
  • 1
    @duektime201823 check this out https://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript – Hari Bharathi Dec 19 '20 at 09:40

2 Answers2

1

You can do it by

var table = document.getElementById('table');

for (var r = 0, n = table.rows.length; r < n; r++) {
    for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
        var image = document.createElement("img");

        if(table.rows[r].cells[c].innerHTML === "Up"){               
           image.src = "/your_image_path_for_up";
        } else {
           image.src = "/your_image_path_for_down";               
        }

        var newCell = row.insertCell(c+1);
        newCell.appendChild(image);

    }
}

This will append a new cell with an image to the right of your cell with "Up" or "Down".

Lee Boon Kong
  • 662
  • 1
  • 6
  • 16
0

Below is the script, which will find all of the cells, loop through them and add appropriate image

<script>
   var cells = document.querySelectorAll('td');
   for (var i = 0; i < cells.length; i++) {
     var cell = cells[i];
     var cellContent = cell.textContent.toLowerCase().trim();
     var img = document.createElement('img')
     if (cellContent === 'up') {
        img.src = 'src_to_up_arrow_image';
     } else if (cellContent === 'down') {
        img.src = 'src_to_down_arrow_image';
     };
     cell.appendChild(img);
   }
 </script>