HL.
HL.

Reputation: 614

Change CSS class declaration or actually apply style to every element?

I have a table with over 400 rows and about 90 columns. The visibility of the columns should be dynamic. I already assigned a css class .column(x) to every cell, where (x) is the column's index/count. Now i can change visibility in two ways:

$('.column5').css('display','block');

But that has to loop over 400 cells and possibly re-render the html on every iteration (?). The other method is:

$('.style').html().replace('.column5{display:none}','.column5{display:block}');

Where

<style class='style'>
 .column1{display:none}
 .column2{display:none}
 .column3{display:none}
 .column4{display:none}
 .column5{display:none}
 ...
</style>

I'm using the first method now, but it's naturally quite slow with so many cells to change. The question is: could there be any performance gain from using the second method? Does it even make sense/is it a bad practice?
Thanks in advance!

Upvotes: 0

Views: 109

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

I wouldn't do either. Instead, I'd have rules in the CSS like this:

.hide-column5 .column5 {
    display: none;
}

...and then toggle the hide-column5 class on the container of the cells (e.g., the table or tbody as appropriate).

Example:

$("input[type=checkbox]").on("click", function() {
    var cls = this.getAttribute("data-cls");
    $("table").toggleClass(cls, !this.checked);
});
.hide-column1 .column1 {
  display: none;
}
.hide-column2 .column2 {
  display: none;
}
.hide-column3 .column3 {
  display: none;
}
<table>
  <thead>
    <tr>
      <th class="column1">Col 1</th>
      <th class="column2">Col 2</th>
      <th class="column3">Col 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="column1">1</td>
      <td class="column2">2</td>
      <td class="column3">3</td>
    </tr>
    <tr>
      <td class="column1">1</td>
      <td class="column2">2</td>
      <td class="column3">3</td>
    </tr>
    <tr>
      <td class="column1">1</td>
      <td class="column2">2</td>
      <td class="column3">3</td>
    </tr>
  </tbody>
</table>
<div>
  <label>
    <input checked type="checkbox" data-cls="hide-column1"> Show 1
  </label>
</div>
<div>
  <label>
    <input checked type="checkbox" data-cls="hide-column2"> Show 2
  </label>
</div>
<div>
  <label>
    <input checked type="checkbox" data-cls="hide-column3"> Show 3
  </label>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions