Search code examples
javascriptjquerycsshide

If td paragraph has class, hide tr class


I need to hide (display:none;) an entire <tr> if the paragraph contained within the <td> has a specific class.

Example:

<table>
    <tbody>
        <tr id="sample-34457" class="row-class">
            <td class="cell-class"></td>
            <td class="cell-class"></td>
            <td class="cell-class">
                <p class="hide-tr-if-class"></p>
            </td>
        </tr>
    </tbody>
</table>

I have tried some methods using CSS but it doesn't work 100% of the time.

Some jQuery I have tried:

if ($("p").hasClass(".hide-tr-if-class") ) {
    $("tr#sample-*").hide();

    ///// OR

    $(".row-class").css("display"`, "none");

};

No real luck with either attempt. My goal is to hide the entire table row using display:none if the paragraph has the class. This will remove items from a list in the end if conditions are met.

Thanks.


Solution

  • First, if you use hasClass, the parameter will not need a .

    Moreover, use closest to select the closest parent (here tr)

    if ($('p').hasClass('hide-tr-if-class')) {
      console.log('in here')
      $('p.hide-tr-if-class').closest('tr').css('visibility', 'hidden');
    };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tbody>
        <tr id="sample-34457" class="row-class">
          <td class="cell-class">a</td>
          <td class="cell-class">b</td>
          <td class="cell-class">
            <p class="hide-tr-if-class">c</p>
          </td>
        </tr>
        <tr id="sample-34457" class="row-class">
          <td class="cell-class">d</td>
          <td class="cell-class">e</td>
          <td class="cell-class">
            <p class>f</p>
          </td>
        </tr>
      </tbody>
    </table>