views:

17

answers:

1

Hello,

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:

  • table
    • tr
      • td A
      • td B
    • tr
      • td C
        • input D

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.

+1  A: 

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.

Ken Redler
Thanks Ken! I think this will work just fine for this case. You rock!
ianneub