Search code examples
jqueryhtmlhtml-tableparentclosest

JQuery find closest parent tr in nested tr


How can I find the parent tr from the closest child tr e.g. from the second child tr, how can I get to the first parent tr?

Below are two table structures I have been using:

1)

 <table>
        <tr class="menu">
            <td><input type='text' class='parent' value='First Parent'></td>  
            <tr class="sub-menu">
                <td><input type='text' class='firstchild' value='First Child'>
                </td>

            </tr>
             <tr class="sub-menu">
                <td><input type='text' class='secondchild' value='Second Child'>
                </td>
            </tr>   
        </tr>
            <tr class="menu" >
            <td ><input type='text' class='parent' value='Second Parent'></td> 
            <tr class="sub-menu">
                <td><input type='text' class='firstchild' value='First Child'>
                </td>
                </tr>
            </tr>
    </table>

2)

    <table>
    <tr class="menu">
        <td><input type='text' class='parent' value='First Parent'></td>  
</tr>
        <tr class="sub-menu">
            <td><input type='text' class='child' value='First Child'>
            </td>
      </tr>

         <tr class="sub-menu">
            <td><input type='text' class='child' value='Second Child'>
            </td>
        </tr>   
    <tr  class="menu">

        <td><input type='text' class='parent' value='Second Parent'></td>  </tr>
        <tr class="sub-menu">
            <td><input type='text' class='child' value='First Child'>
            </td>
            </tr>

</table>

I have tried the following JQuery code:

$(this).closest('tr.submenu').closest('tr.menu').find('.parent').val();

$(this).closest('tr.submenu').parent('tr.menu').find('.parent').val();

$(this).closest('tr.menu').find('.parent').val();

$(this).closest('tr.submenu').prevUntil('tr.menu').find('.parent').val();

$(this).closest('tr.submenu').parentsUntil('tr.menu').find('.parent').val();

$(this).closest('tr.submenu').parents(':first-child').find('.parent').val();

All attempts have failed. How can I get the parent value from the closest sub menu tr?


Solution

  • found the solution:

    $('.child').click(function() {
        var $this = $(this);
    
        $this.parents('tr').prevAll("tr.menu:first").css("background-color", "yellow");
    
    });