How to find all Siblings of the currently selected DOM object

前端 未结 11 1325
轻奢々
轻奢々 2020-12-08 04:25

What is the perfect way to find all nextSiblings and previousSiblings in JavaScript. I tried few ways but not getting accurate solution. If any element is selected, I need t

11条回答
  •  佛祖请我去吃肉
    2020-12-08 05:16

    All previous siblings

    // jQuery (optional filter selector)
    $el.prevAll($filter);
    
    // Native (optional filter function)
    function getPreviousSiblings(elem, filter) {
      var sibs = [];
      while (elem = elem.previousSibling) {
          if (elem.nodeType === 3) continue; // ignore text nodes
          if (!filter || filter(elem)) sibs.push(elem);
      }
      return sibs;
    }
    

    All next siblings

    // jQuery (optional selector filter)
    $el.nextAll($filter);
    
    // Native (optional filter function)
    function getNextSiblings(elem, filter) {
            var sibs = [];
            var nextElem = elem.parentNode.firstChild;
            do {
                if (nextElem.nodeType === 3) continue; // ignore text nodes
                if (nextElem === elem) continue; // ignore elem of target
                if (nextElem === elem.nextElementSibling) {
                    if (!filter || filter(elem)) {
                        sibs.push(nextElem);
                        elem = nextElem;
                    }
                }
            } while(nextElem = nextElem.nextSibling)
            return sibs;
        }
    

    An example of filter function:

    function exampleFilter(elem) {
      switch (elem.nodeName.toUpperCase()) {
        case 'DIV':
          return true;
        case 'SPAN':
          return true;
        default:
          return false;
      }
    }
    

提交回复
热议问题