Heisenberg
Heisenberg

Reputation: 5299

How to undo class change in html table

When I try to undo class change,I suffer some problems.

I could get clicked element, but my desired result is to get class changed element and undo it.

For example in my snippet,I would like to undo all the class change at the same time.

In other words, I would like to getclass changed element array.

Are there any method?

Thanks

let clicked=[];

$(function() {
  $("td").click(function() {
    $(this).nextAll(':lt(4)').addClass('color');
     let clickedID=$(this).attr('id');
     clicked.push(clickedID);
});
});

$(function() {
  $("#btnCancel").on('click',() => {
    if(clicked.length) {
      let lastClicked = clicked.pop();
      $(`td#${lastClicked}`).removeClass();
    }
  });
  });
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}
.color {
  background-color: hsl(60,100%,60%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
<tr>
<td id=1>1</td>
<td id=2>2</td>
<td id=3>3</td>
<td id=4>4</td>
<td id=5>5</td>
<td id=6>6</td>
<td id=7>7</td>
<td id=8>8</td>
<td id=9>9</td>
</tr>
</table>

<button id="btnCancel">undo</button>

Upvotes: 2

Views: 220

Answers (1)

Rayon
Rayon

Reputation: 36609

.removeClass([className]) Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

$('td#${lastClicked}').nextAll(':lt(4)').removeClass('color'); would return the last selected/updated elements.

let clicked = [];

$(function() {
  $("td").click(function() {
    $(this).nextAll(':lt(4)').addClass('color');
    let clickedID = $(this).attr('id');
    clicked.push(clickedID);
  });
});

$(function() {
  $("#btnCancel").on('click', () => {
    if (clicked.length) {
      let lastClicked = clicked.pop();
      $(`td#${lastClicked}`).nextAll(':lt(4)').removeClass('color');
    }
  });
});
table td {
  width: 20px;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  border: 1px solid gray;
  text-align: center;
  padding: 5px;
  cursor: pointer;
}

.color {
  background-color: hsl(60, 100%, 60%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td id=1>1</td>
    <td id=2>2</td>
    <td id=3>3</td>
    <td id=4>4</td>
    <td id=5>5</td>
    <td id=6>6</td>
    <td id=7>7</td>
    <td id=8>8</td>
    <td id=9>9</td>
  </tr>
</table>

<button id="btnCancel">undo</button>

Upvotes: 4

Related Questions