Help Inspire
Help Inspire

Reputation: 366

Odd Table Row Behavior

My Javascript is quite basic, but for some reason I am having trouble. I have a table that is dynamically being built and the goal of my script is to select the last 5 rows if there are more then 10 total rows and apply a CSS style to those final five. I built a stripped down example where the first 5 rows should be made blue and the last 5 rows made red. http://jsfiddle.net/helpinspireme/3zCp8/

There is probably a much better way to do this. Any help would be appreciated.

ANSWER:
Using slice() allowed me to accomplish my goal. That can be seen here: http://jsfiddle.net/helpinspireme/3zCp8/ Thank you Kevin B.

Upvotes: 0

Views: 76

Answers (2)

Kevin B
Kevin B

Reputation: 95030

For what you explained you are trying to do in your question, the simplest way to accomplish it is:

var rows = $("table.primary_table > tbody > tr");
if (rows.length > 10) {
    rows.filter(":lt(5)").css("background-color", "blue")
        .end()
        .slice(-5).css("background-color", "red");
}

http://api.jquery.com/slice

Upvotes: 2

Thomas
Thomas

Reputation: 8849

Without looking at the code for too long I guess you're looking for the gt and lt selectors.

Edit: since you're getting all rows anyway slice() would probably be better.

Upvotes: 0

Related Questions