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.

3
  • 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. Commented Dec 19, 2020 at 9:28
  • @WaisKamal Thank you, I should give this a run for a few days and follow up on my findings. Commented Dec 19, 2020 at 9:31
  • 1
    @duektime201823 check this out stackoverflow.com/questions/3065342/… Commented Dec 19, 2020 at 9:40

2 Answers 2

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".

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.