HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Select the one table before my link

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thebeforeoneselecttablelink

Problem

I need to select the `` 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/

Solution

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.

Context

StackExchange Code Review Q#64385, answer score: 3

Revisions (0)

No revisions yet.