2

So what I'm trying to do is get the last row of an HTML table. If this row then has a certain class I will ignore this row and select the previous one. This would then be cycled through from the end of the table until a row was found without this certain class.

I figured it's probably involving a for loop, a check for the row class and then JQuery's row.prev method, but still not quite sure how to approach this.

Thanks in advance!

2
  • What's on the server-side generating the Html table? Commented Dec 28, 2011 at 15:34
  • With jQuery it's a one-liner as shown below. Without jQuery it's still only about three or four lines using a for loop over the table.rows collection, checking the class and breaking out of the loop when found. Commented Dec 28, 2011 at 15:45

3 Answers 3

3

To get the last table row that doesn't have a certain class, say targetClass, you can do this:

$("tr:not(.targetClass):last");

I'm not sure what you want to do with this table row, but if you were to add targetClass to the last row that didn't have it, it would look like this

$("tr:not(.targetClass):last").addClass("targetClass");

Check out this fiddle to see it in action

Sign up to request clarification or add additional context in comments.

Comments

2

This example shows you how to get the last of each table on the current page: http://jsfiddle.net/JBnzK/

$('table').find('tr:last').each(function(){
    if ($(this).hasClass('stupid')) {
        $(this).css('color', 'red');
    } else {
        $(this).css('color', 'green');
    }
});

Comments

1

Assuming you've got the following HTML:

<table id="mytable">
    <tbody>
        <tr>
            <td>1</td>
        </tr>
        <tr id="YouFoundMe">
            <td>1</td>
        </tr>
        <tr class="certainclass">
            <td>1</td>
        </tr>
        <tr class="certainclass">
            <td>1</td>
        </tr>
        <tr class="certainclass">
            <td>1</td>
        </tr>

    </tbody>
</table>

You can do this:

var elWithoutClass = $('#mytable tr:not(.certainclass):last');

if (elWithoutClass.length) {
    alert(elWithoutClass.get(0).id);
    // alerts "YouFoundMe"
}
  • :not(.certainclass) will eliminate <tr> without class 'certainclass'
  • :last will get you the last one

I invite you to check the Selectors documentation page of jquery to learn more about them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.