Jquery Get last row of table within last element i

2020-07-10 09:36发布

I have a series of slides based off of sections:

<div id="slides">
    <section id="first">
        <section>
            <table>
                <thead>
                </thead>
                <tbody>
                    <tr id="somethingUnique">
                    ...
                    </tr>
                </tbody>
            </table>
        </section>
        <section>
            <table>
                <thead>
                </thead>
                <tbody>
                    <tr id="somethingUnique">
                    ...
                    </tr>
                </tbody>
            </table>
        </section> 
       ...
    </section>
</div>

I need to select grab the ID of the last row from the table in the last section of #first section.

I'm using the following Jquery, getting "undefined" back...any ideas?

    var lastListItem = $('#first:last-child table>tbody>tr:last').attr("id");
    alert(lastListItem);

5条回答
forever°为你锁心
2楼-- · 2020-07-10 09:57

.find():

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

​$("#first")​.find("tr:last").attr("id")

or more simply in this case:

$("#first tr:last").attr("id")

EXAMPLE

查看更多
我想做一个坏孩纸
3楼-- · 2020-07-10 10:02
var lastListItem = $("#first").find("section").last().find("tr").last().attr("id");

I prefer using [0].id instead of .attr("id") since its one less method call; however, if you're not positive that you'll always have a table in that DOM position, attr is safer.

查看更多
We Are One
4楼-- · 2020-07-10 10:06

The other answers work but the problem with your attempt is the fact that :last-child has to be applied to the child element (section), not the parent (#first). The following should work

$('#first section:last-child table>tbody>tr:last').attr("id");

And could be simplified to

$('#first section:last-child tr:last-child').attr("id");

http://jsfiddle.net/e7mUD/1

查看更多
冷血范
5楼-- · 2020-07-10 10:07
var lastListItem = $('#first section:last  table tr:last').attr("id");
查看更多
倾城 Initia
6楼-- · 2020-07-10 10:10
$('#first table:last tr:last')

or:

$('#first tr:last')

http://jsfiddle.net/hunter/QMzHH/

查看更多
登录 后发表回答