group html table rows with enclosing tag

Viewed 10329

I want to be able to access a subgroup of rows in a html table using a common property assigned to them – let's say I want a pair of rows to disappear using javascript. If it had worked, enclosing those rows with a div and assigning that div to a class would been perfect.

<table>
  <tbody>
    <tr>...</tr>
    <div class="hideme_sometimes">
      <tr>...</tr>
      <tr>...</tr>
    </div>
    <tr>...</tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){$("div.hideme_sometimes").hide();}); 
</script>

But obviously you can't put parts of a table inside a div, or a span. Is there some other way of grouping <tr> elements to the same effect?

4 Answers

You can have multiple tbody elements which can surround the rows.

document.querySelector("button").addEventListener("click", function(){
    this.setAttribute("hidden", true)
    document.querySelectorAll("tbody")[1].removeAttribute("hidden")
});
<table>
  <thead>
    <tr>
      <th>foo</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
    </tr>
    <tr>
      <td>2</td>
    </tr>
  </tbody>
  <tbody hidden>
    <tr>
      <td>3</td>
    </tr>
    <tr>
      <td>4</td>
    </tr>
  </tbody>
</table>

<button type="button">more</button>

You could just put a class on them, and query by class, so

$("div.hideme_sometimes").hide();

becomes

$("tr.hideme_sometimes").hide();

How about assigning class=hideme_sometimes to each of the rows and calling $(".hideme_sometimes").hide();

In some cases it may be convenient to use data-* attributes.

Rows in the same group could be assigned the same index, for example:

<tr data-group-index="0">...</tr>

and you can select a group of rows using CSS attribute selectors, for example:

document.querySelectorAll('tr[data-group-index="0"]')

Once you have selected a <tr> element (as row), you can either read (and write) the attribute value using getAttribute (and setAttribute) or you can use the dataset property:

row.getAttribute('data-group-index') === row.dataset.groupIndex
Related