Find closest previous element jQuery

前端 未结 5 530
一向
一向 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条回答
  •  Happy的楠姐
    2020-12-14 06:55

    var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
    

    Example: http://jsfiddle.net/e27r8/

    This uses the closest()[docs] method to get the first ancestor that has a nested h3 span b, then does a .find().

    Of course you could have multiple matches.


    Otherwise, you're looking at doing a more direct traversal.

    var link = $("#me").closest("h3 + div").prev().find('span b');
    

    edit: This one works with your updated HTML.

    Example: http://jsfiddle.net/e27r8/2/


    EDIT: Updated to deal with updated question.

    var link = $("#me").closest("h3 + *").prev().find('span b');
    

    This makes the targeted element for .closest() generic, so that even if there is no parent, it will still work.

    Example: http://jsfiddle.net/e27r8/4/

提交回复
热议问题