Find closest previous element jQuery

前端 未结 5 531
一向
一向 2020-12-14 06:33

I am wanting something similar to this person, except the element I want to match might not be a direct sibling.

If I had this HTML, for example,

<         


        
5条回答
  •  再見小時候
    2020-12-14 07:13

    I know this is old, but was hunting for the same thing and ended up coming up with another solution which is fairly concise andsimple. Here's my way of finding the next or previous element, taking into account traversal over elements that aren't of the type we're looking for:

    var ClosestPrev = $( StartObject ).prevAll( '.selectorClass' ).first();
    var ClosestNext = $( StartObject ).nextAll( '.selectorClass' ).first();
    

    I'm not 100% sure of the order that the collection from the nextAll/prevAll functions return, but in my test case, it appears that the array is in the direction expected. Might be helpful if someone could clarify the internals of jquery for that for a strong guarantee of reliability.

提交回复
热议问题