1

I'm using this answer to include a toggle that switches between two css classes: twotablecell and tablecell which are two different sized table headers cells which are different sizes in css.

When clicking on my button id: sizeTog, it changes the table headers class property to tablecell however does not change it back to twotablecell when clicking on it again.

$('#sizeTog').on('click', function() {
  $('table thead tr .twotablecell').toggleClass("twotablecell tablecell");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th class="twotablecell">
        Name
      </th>
    </tr>
  </thead>
</table>

<input id="sizeTog" type="button" value="toggle size">

I've tried changing the element that needs to be toggled to: table thead tr th.twotablecell to make it more specific.

It only works accordingly when I change the Jquery toggled element to table thead tr th.

However, this is I have quite a few different table header columns which I want to be different sizes other than twotablecell and tablecell.

Rob
  • 2,243
  • 4
  • 29
  • 40
hello world
  • 306
  • 1
  • 6
  • 28

1 Answers1

2

The problem is because on the second click the element you're looking for doesn't have the .twotablecell class any more - the first click removed it.

Select it by another means, using a different class which is not removed for example:

$('#sizeTog').on('click', function() {
  $('table thead tr .headercell').toggleClass("twotablecell tablecell");
});
.tablecell { color: #C00; }
.twotablecell { color: #0C0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th class="headercell twotablecell">
        Name
      </th>
    </tr>
  </thead>
</table>

<input id="sizeTog" type="button" value="toggle size">
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339