jquery - get all rows except the first and last

前端 未结 6 650
暗喜
暗喜 2020-12-23 09:11

i want to dynamically add a class to all rows of a table except the first and last row. how would i do this without assigning a css class to the rows to identify them. I a

6条回答
  •  旧时难觅i
    2020-12-23 10:03

    Drop the gt(), as I'd assume it's a tiny bit slower than :first.

    Use not() in conjunction with :first and :last:

    $('table#tbl > tbody > tr').not(':first').not(':last').addClass('highlight');
    

    Most browsers automatically add an tbody element in the table markup if that's missing, that is why the immediate children selector was failing – there were no elements as an immediate children to the

    tag.

    I am not 100% sure this is the way all browsers do it, so it would be safer to just add the

    manually. Otherwise you need a little sniffing and cannot do it as an one liner:

    if($('table#tbl > tbody').size() > 0) {
        $('table#tbl > tbody > tr').not(':first').not(':last').addClass('highlight');
    } else {
        $('table#tbl > tr').not(':first').not(':last').addClass('highlight');
    }
    

    Hope this solves your problem!

    提交回复
    热议问题