获取同级元素

获取当前 DOM 元素同级元素


一个辅助函数,用于获取给定DOM元素的所有同级兄弟或一组经过过滤的同级兄弟:


function getSiblings(el, filter) {
  var siblings = [];
  el = el.parentNode.firstChild;
  do { if (!filter || filter(el)) siblings.push(el); } while (el = el.nextSibling);
  return siblings;
}

// example filter function
function exampleFilter(el) {
  return elem.nodeName.toLowerCase() == 'a';
}

// usage
el = document.querySelector('div');
// get all siblings of el
var sibs = getSiblings(el);
// get only anchor element siblings of el
var sibs_a = getSiblings(el, exampleFilter);
      

更快的DOM方法仅用于获取元素的上一个或下一个同级:


var previous = el.previousSibling;
var next = el.nextSibling;
      

获取元素的所有以下同级元素,可以选择性的对其进行过滤:


// this helper accepts a filter function as shown above: "exampleFilter()"
function getNextSiblings(el, filter) {
    var siblings = [];
    while (el= el.nextSibling) { if (!filter || filter(el)) siblings.push(el); }
    return siblings;
}
      

获取元素的所有同级之前的原序,可选地进行过滤:


// this helper accepts a filter function as shown above: "exampleFilter()"
function getPreviousSiblings(el, filter) {
    var siblings = [];
    while (el = el.previousSibling) { if (!filter || filter(el)) siblings.push(el); }
    return siblings;
}