jQuery to find all previous elements that match an expression

后端 未结 5 2046
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 16:21

Using jQuery, how do you match elements that are prior to the current element in the DOM tree? Using prevAll() only matches previous siblings.<

5条回答
  •  隐瞒了意图╮
    2020-12-05 16:44

    Presumably you are doing this inside an onclick handler so you have access to the element that was clicked. What I would do is do a prevAll to see if it is at the same level. If not, then I would do a parent().prevAll() to get the previous siblings of the parent element, then iterate through those backwards, checking their contents for the desired element. Continue going up the DOM tree until you find what you want or hit the root of the DOM. This a general algorithm.

    If you know that it is inside a table, then you can simply get the row containing the element clicked and iterate backwards through the rows of the table from that row until you find one that contains the element desired.

    I don't think there is a way to do it in one (chained) statement.

提交回复
热议问题