Skip to content

Instantly share code, notes, and snippets.

@cs09g
Last active September 13, 2018 01:26
Show Gist options
  • Save cs09g/70bd9725e9befac992255a673f7554e4 to your computer and use it in GitHub Desktop.
Save cs09g/70bd9725e9befac992255a673f7554e4 to your computer and use it in GitHub Desktop.
vanilla script prev from jquery prev
/*
* It returns previous element sibling
* works like jquery's `prev` but combined selector is not supported
*
*/
var prev = function(target, selector) {
var siblings = target.parentNode.children;
var previousElementSibling;
for (var i = Array.prototype.indexOf.call(siblings, target) - 1; i >= 0; i--) {
if (selector[0] === ".") {
if (siblings[i].classList.contains(selector.substr(1))) {
previousElementSibling = siblings[i];
break;
}
} else if (selector[0] === "#") {
if (siblings[i].id === selector.substr(1)) {
previousElementSibling = siblings[i];
break;
}
} else {
if (siblings[i].tagName.toLowerCase() === selector) {
previousElementSibling = siblings[i];
break;
}
}
}
return previousElementSibling;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment