JSFiddle - React, Tailwind, and code Playground

by Mottie

HTML

<div id='test'>
  <div id='test2'>asdf</div>
  <br /> sdf
  <div>asdfasdf<span>asdf</span></div>
  <div>a</div>
  <span>a</span>
  <br />
  <div>d</div>
  <hr/>
</div>

CSS

/*
see http://stackoverflow.com/a/37470381/145346
*/

JavaScript

function matches(elem, filter) {
  if (elem && elem.nodeType === 1) {
    if (filter) {
      return elem.matches(filter);
    }
    return true;
  }
  return false;
}

// this will start from the current element and get all of the next siblings
function getNextSiblings(elem, filter) {
  var sibs = [];
  while (elem = elem.nextSibling) {
    if (matches(elem, filter)) {
      sibs.push(elem);
    }
  }
  return sibs;
}

//this will start from the current element and get all the previous siblings
function getPreviousSiblings(elem, filter) {
  var sibs = [];
  while (elem = elem.previousSibling) {
    if (matches(elem, filter)) {
      sibs.push(elem);
    }
  }
  return sibs;
}

// this will start from the first child of the current element's
// parent and get all the siblings
function getAllSiblings(elem, filter) {
  var sibs = [];
  elem = elem.parentNode.firstChild;
  while (elem = elem.nextSibling) {
    if (matches(elem, filter)) {
      sibs.push(elem);
    }
  } 
  return sibs;
}

var elem;
elem = document.getElementById('test2');

//with filter alerts 4
console.log('next with filter (4)', getNextSiblings(elem, 'div, span').length);

elem = document.getElementById('test2'); // put elem back to what it was
// no filter, alerts 7
console.log('next no filter (7)', getNextSiblings(elem).length);

elem = document.getElementById('test2'); // put elem back to what it was
// alerts 0
console.log('prev with filter (0)', getPreviousSiblings(elem, 'div, span').length);
elem = document.getElementById('test2'); // put elem back to what it was
// alerts 5
console.log('get all with filter (5)', getAllSiblings(elem, 'div, span').length);