Last active
September 13, 2018 01:26
-
-
Save cs09g/70bd9725e9befac992255a673f7554e4 to your computer and use it in GitHub Desktop.
vanilla script prev from jquery prev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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