HopAlongPolly
HopAlongPolly

Reputation: 1433

Using JQuery to select all <tr> elements with a specific class

The basic structure is a table with a few rows. I would like the top half of the table showing and the bottom half collapsed until a user clicks on the READ MORE cell. I have that functionality working but I can't get the JQuery right that selects all of the ".collapseThis" rows and hides them on page load.

Here is the table

<div id="tables">
    <table class="expandableTable">
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr class="accordion">
            <td colspan="2">READ MORE</td>
        </tr>
        <tr class="collapseThis">
            <td></td>
            <td></td>
        </tr>
    </table>
    <table class="expandableTable">
        <tr>
            <td></td>
            <td></td>
        </tr>
        <tr class="accordion">
            <td colspan="2">READ MORE</td>
        </tr>
        <tr class="collapseThis">
            <td></td>
            <td></td>
        </tr>
    </table>
</div>

Here is the JQuery.

$(document).ready(function () {

    function getCollapsable($row) {
        var children = [];
        while ($row.next().hasClass('collapseThis')) {
            children.push($row.next());
            $row = $row.next();
        }
        return children;
    }

    function hideTableRows($row) {
        children = getCollapsable($row);
        $.each(children, function () {
            $(this).toggle();
        });
    }

    $('#tables').each($('expandableTable'), function () {
        hideTableRows($(this).children().hasClass('.accordion'));
});

Upvotes: 1

Views: 1756

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can just use css to set the display value, there is no need to use jQuery to set the initial state.

If you want to use jQuery, use a simple selector like $('#tables .expandableTable .collapseThis').hide().

$(document).ready(function() {

  //if you don't want to use css
  //$('#tables .expandableTable .collapseThis').hide();
});
#tables .expandableTable .collapseThis {
  display: none;
}
<div id="tables">
  <table class="expandableTable">
    <tr>
      <td>1.1</td>
      <td>1.2</td>
    </tr>
    <tr class="accordion">
      <td colspan="2">READ MORE</td>
    </tr>
    <tr class="collapseThis">
      <td>2.1</td>
      <td>2.2</td>
    </tr>
  </table>
  <table class="expandableTable">
    <tr>
      <td>1.1</td>
      <td>1.2</td>
    </tr>
    <tr class="accordion">
      <td colspan="2">READ MORE</td>
    </tr>
    <tr class="collapseThis">
      <td>2.1</td>
      <td>2.2</td>
    </tr>
  </table>
  <table class="expandableTable">
    <tr>
      <td>1.1</td>
      <td>1.2</td>
    </tr>
    <tr class="accordion">
      <td colspan="2">READ MORE</td>
    </tr>
    <tr class="collapseThis">
      <td>2.1</td>
      <td>2.2</td>
    </tr>
  </table>
</div>

Upvotes: 3

Related Questions