Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 12:59
Show Gist options
  • Save ianpgall/6134845 to your computer and use it in GitHub Desktop.
Save ianpgall/6134845 to your computer and use it in GitHub Desktop.
JavaScript function that gets an Element's first following sibling (that matches a selector, optionally). If a selector is provided, it searches through all following siblings for the element that matches the selector (if any)
var NextElementSibling = (function () {
"use strict";
var E, supportsNativeNext, is, traverseAcross, ret;
E = document.createElement("div");
supportsNativeNext = ("nextElementSibling" in E && !E.hasOwnProperty("nextElementSibling"));
is = (function () {
var prefixes, i, j, cur, matchProp, matchFunc;
prefixes = ["webkit", "moz", "ms", "o"];
for (i = 0, j = prefixes.length; i < j; i++) {
cur = prefixes[i] + "MatchesSelector";
if (E[cur] && !E.hasOwnProperty(cur)) {
matchProp = cur;
break;
}
}
if (matchProp) {
matchFunc = function (el, sel) {
return el[matchProp](sel);
};
} else {
matchFunc = function (el, sel) {
var matches;
E.appendChild(el.cloneNode(false));
matches = E.querySelector(sel);
E.removeChild(E.firstChild);
return matches;
};
}
return matchFunc;
}());
traverseAcross = function (el, prop, sel) {
do {
el = el[prop];
} while (el && (el.nodeType !== 1 || (sel && !is(el, sel))));
return el;
};
ret = function (element, selector) {
var property = supportsNativeNext ? "nextElementSibling" : "nextSibling";
element = traverseAcross(element, property, selector);
return element;
};
return ret;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment