How to implement “prevUntil” in Vanilla JavaScript without libraries?

前端 未结 7 1053
遇见更好的自我
遇见更好的自我 2020-12-29 11:32

I need to implement the functionality of jQuery\'s prevUntil() method in Vanilla JavaScript.

I\'ve got several

elements on the same level:
7条回答
  •  佛祖请我去吃肉
    2020-12-29 11:54

    Just take a look at how jQuery does it.

    prevUntil: function( elem, i, until ) {
        return jQuery.dir( elem, "previousSibling", until );
    },
    

    Which uses a while / looping function caled dir(). The prevUntil just keeps going until previousSibling is the same as the until element.

    dir: function( elem, dir, until ) {
        var matched = [],
            cur = elem[ dir ];
    
        while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
            if ( cur.nodeType === 1 ) {
                matched.push( cur );
            }
            cur = cur[dir];
        }
        return matched;
    },
    

提交回复
热议问题