How to select lines 1 through N above

2

I have a dynamically generated table in the following schema:

<table>
  <tr class="row-1">
    <td>A</td>
    <td>1</td>
  </tr>
  <tr class="row-2">
    <td>B</td>
    <td>2</td>
  </tr>
  <tr class="row-3">
    <td>C3</td>
    <td></td>
  </tr>
  <tr class="row-total">
    <td>
      <input type="button" value="Toogle">
    </td>
    <td>TOTAL</td>
  </tr>

  <tr class="row-1">
    <td>D</td>
    <td>4</td>
  </tr>
  <tr class="row-2">
    <td>E</td>
    <td>5</td>
  </tr>
  <tr class="row-3">
    <td>F</td>
    <td>6</td>
  </tr>
  <tr class="row-total">
    <td>
      <input type="button" value="Toogle">
    </td>
    <td>TOTAL</td>
  </tr>

</table>

In this table I will only display the line with the total value, and the previous ones will be hidden and will only be displayed by a toggle.

Should I use nth-child or is there another way to do this?

    
asked by anonymous 24.05.2016 / 20:30

1 answer

2

You can use this:

$('input').on('click', function() {
    $(this).closest('tr').prevAll().each(function(){
        if (this.classList.contains('row-total')) return false;
        $(this).toggle();
    });
});

Using .closest() you will get tr containing input clicked.

Using .prevAll() you will search all tr previous.

Giving return false; inside a jQuery loop causes it to stop the loop, so do not go looking for the previous elements.

To hide all in the beginning is enough:

tr {
    display: none;
}
tr.row-total {
    display: block;
}

Example: link

    
24.05.2016 / 20:45