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
- td C
- tr
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.
精彩评论