jQuery to find all previous elements that match an expression

后端 未结 5 2051
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    had the same problem, heres what i came up with. my function uses compareDocumentPosition. dont know how it compares to the other solutions in terms of performance though.

    $.fn.findNext = function ( selector ) {
      var found, self = this.get(0);
      $( selector )
        .each( function () {
          if ( self.compareDocumentPosition( this ) === 4 ){ 
            found = this; 
            return false;
          }    
        })
      return $(found);
    }
    

    of course one could change this quite easily to fetch ALL elements following the calling element.

    $.fn.nextALL= function ( selector ) {
      var found = [], self = this.get(0);
      $( selector )
        .each( function () {
          if ( self.compareDocumentPosition( this ) === 4 )
            found.push(this);          
        })
      return $(found);
    }
    

    EDIT: streamlined version

    $.fn.findNext = function( s ){
        var m = this[0], f=function(n){return m.compareDocumentPosition(n)===4;};
        return this.pushStack( $(s).get().filter(f) );
    }
    

提交回复
热议问题