4
\$\begingroup\$

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/

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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