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

前端 未结 7 907
遇见更好的自我
遇见更好的自我 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 12:02

    This answer was previously published here in response to a similar question .

    There are a few ways to do it.

    Either one of the following should do the trick.

    // METHOD A (ARRAY.FILTER, STRING.INDEXOF)
    var siblings = function(node, children) {
        siblingList = children.filter(function(val) {
            return [node].indexOf(val) != -1;
        });
        return siblingList;
    }
    
    // METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH)
    var siblings = function(node, children) {
        var siblingList = [];
        for (var n = children.length - 1; n >= 0; n--) {
            if (children[n] != node) {
                siblingList.push(children[n]);
            }  
        }
        return siblingList;
    }
    
    // METHOD C (STRING.INDEXOF, ARRAY.SPLICE)
    var siblings = function(node, children) {
       siblingList = children;
       index = siblingList.indexOf(node);
       if(index != -1) {
           siblingList.splice(index, 1);
       }
       return siblingList;
    }
    

    FYI: The jQuery code-base is a great resource for observing Grade A Javascript.

    Here is an excellent tool that reveals the jQuery code-base in a very streamlined way. http://james.padolsey.com/jquery/

提交回复
热议问题