Find closest previous element jQuery

前端 未结 5 536
一向
一向 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 06:51

    No, there is no "easy" way. Your best bet would be to do a loop where you first check each previous sibling, then move to the parent node and all of its previous siblings.

    You'll need to break the selector into two, 1 to check if the current node could be the top level node in your selector, and 1 to check if it's descendants match.

    Edit: This might as well be a plugin. You can use this with any selector in any HTML:

    (function($) {
        $.fn.closestPrior = function(selector) {
            selector = selector.replace(/^\s+|\s+$/g, "");
            var combinator = selector.search(/[ +~>]|$/);
            var parent = selector.substr(0, combinator);
            var children = selector.substr(combinator);
            var el = this;
            var match = $();
            while (el.length && !match.length) {
                el = el.prev();
                if (!el.length) {
                    var par = el.parent();
                    // Don't use the parent - you've already checked all of the previous 
                    // elements in this parent, move to its previous sibling, if any.
                    while (par.length && !par.prev().length) {
                        par = par.parent();
                    }
                    el = par.prev();
                    if (!el.length) {
                        break;
                    }
                }
                if (el.is(parent) && el.find(children).length) {
                    match = el.find(children).last();
                }
                else if (el.find(selector).length) {
                    match = el.find(selector).last();
                }
            }
            return match;
        }
    })(jQuery);
    

提交回复
热议问题