Home > Blockchain >  How to find closest matching adjacent row in a table
How to find closest matching adjacent row in a table

Time:11-01

Using Jquery, how can I find the closest adjacent row matching a pattern.

I have a table of rows, where one row represents the header of the following rows until the next header. I have a click handler from an element within one of the rows. Starting from the element clicked, how can I find the nearest header row?

I tried .closest(".header") but there's no results because it's not a parent. I also can't look for .parent().closest(".header") as there are many rows matching that description.

...
<tr class="header"></tr>
<tr></tr>
<tr></tr> // <-- starting here, find tr above with class "header"
<tr></tr>
<tr class="header"></tr>
<tr></tr>
<tr></tr>
<tr></tr>
...

I am developing an extension and can not change the html.

CodePudding user response:

.prev will search among preceeding siblings, so you can use that and select the last one in the collection:

const prevHeader = $(theTr).prev('.header').last();
  • Related