I need to select the <table> before the table where the link I clicked. I can't use IDs, because I don't want to edit my jQuery every time I add a new table.

but this looks kinda bloated for me:

$(this).closest("table").prevAll("table").first().css( "background", "yellow" );

take a look here: http://jsfiddle.net/syddmxfn/13/


1 Answer 1


I think there's no silver bullet for what you're trying to do. To find the previous table, it's necessary to go up the DOM tree until the first table, and then from there find the previous table.

.closest("table") is optimal and necessary.

On the other hand, it's true that .prevAll("table").first() is a bit awkward. Something like .closestPrevious("table") would be the best. I searched around and couldn't find such. So you're stuck with .prevAll("table").first().

In short, bloated it may be, I think it's the best possible way.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.