开发者

jQuery - Select previous DOM element matching a class, when the DOM element is not in the same tree

I'm trying to use jQuery to access a DOM object that appears earlier in the code from the DOM object that I am starting with. This would ordinarily be easy with jQuery's traversal methods, like .parentsUntil. However, in this case the object I am trying to find is not a parent or sibling of the object I am starting from.

For example, imagine this hierarchy:

Starting at input D is it possible to find the html() of td A when there could be any number of elements between A and D?

Thanks for your help, and I apologize if this is too vague, I'll rewrite the question if needed.


I'm not certain what you're asking (see my comment above). So, assuming you want to find the html content of the td of class A that is closest to element D while also being "above" D in the DOM, you could try something like this:

$('input#D')      // somehow uniquely identify our starting point
  .closest('tr')  // up to the closest enclosing TR
  .prevAll()      // and then get its preceding siblings
  .has('td.B')    // reduce this set to only those containing a td.B
  .last()         // choose the last one (thus closest to 'D')
  .find('td.B')   // now work downward to td.B itself
  .html();        // and get the content

It's off the top of my head, so there's probably a more efficient way to do this (and it's untested), but maybe this gives you some ideas.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜