Search code examples
jqueryhtml-tablejquery-selectorsrow

jQuery select first row in next table from last row current table


How to select next row in next table with jQuery. For example I want go from link 2 to link 3 in second table.

<div class="panel">
    <table>
        <tbody>
            <tr>
                <td>
                    <a href="1.html">1</a>
                </td>
                <td>
                    <a class="current" href="2.html">2</a>
                </td>
            </tr>
        </tbody>
    </table>    
</div>
<div class="panel">
    <table>
        <tbody>
            <tr>
                <td>
                    <a href="3.html">3</a>
                </td>
                <td>
                    <a href="4.html">4</a>
                </td>
            </tr>
        </tbody>
    </table>    
</div>

I use this script but won't select next row in another table and just work in itself table.

$('.current').parents('tr').next().find('a').attr('href')

Solution

  • First of all check for length of next row element in same table if not, then you can traverse to closest div .panel than traversing to tr element.

    You should also use .closest() instead of .parents() to only target closest 1st ancestor:

    var nexttr = $('.current').closest('tr').next();
    if(nexttr.length)
       somehref = nexttr.find('a').attr('href');
    else
       somehref = $('.current').closest('.panel').next().find('a').attr('href')