Reputation: 127
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.
Upvotes: 0
Views: 1402
Reputation: 1057
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".
Upvotes: 1
Reputation: 34
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>
Upvotes: 0