Вы можете сделать это, отслеживая историю:
const history = [];
function addToHistory(e) {
const index = e.target.id;
if (history.indexOf(index) < 0) history.push(index);
color();
}
function undo() {
history.pop();
color();
}
function color() {
const cells = document.getElementsByTagName("td");
for (let i = 0; i < cells.length; i++) {
cells[i].classList.remove("red");
}
history.forEach(index => {
document.getElementById(index).className = "red";
});
}
.red{
background-color: red;
}
td {
padding: 5px
}
<table>
<td onclick="addToHistory(event)" id="1">1</td>
<td onclick="addToHistory(event)" id="2">2</td>
<td onclick="addToHistory(event)" id="3">3</td>
<td onclick="addToHistory(event)" id="4">4</td>
<td onclick="addToHistory(event)" id="5">5</td>
<td onclick="addToHistory(event)" id="6">6</td>
<td onclick="addToHistory(event)" id="7">7</td>
<td onclick="addToHistory(event)" id="8">8</td>
<td onclick="addToHistory(event)" id="9">9</td>
<td onclick="addToHistory(event)" id="10">10</td>
</table>
<button onclick="undo()">cancel</button>