Skip to content

Instantly share code, notes, and snippets.

@obiPlabon
Last active September 4, 2016 07:27
Show Gist options
  • Save obiPlabon/8ab74087e4396df5e2eb1a4ae2f0d4ab to your computer and use it in GitHub Desktop.
Save obiPlabon/8ab74087e4396df5e2eb1a4ae2f0d4ab to your computer and use it in GitHub Desktop.
Helpful DOM utility functions in venilla JS
// Code written by Me and
// doc written by Zafree [http://github.com/zafree] vai :D
// Get Siblings
// It is a simple function to get all child from parent
// Feel free to use it like a Pro
function getSiblings(node) {
var childNodes, siblings;
childNodes = node.parentNode.childNodes;
siblings = [];
for (var i=0, len=childNodes.length; i<len; i++ ) {
if (childNodes[i].nodeType == 1 && node != childNodes[i]) {
siblings.push(childNodes[i]);
}
}
return siblings;
}
function addClassToSiblings(node, className) {
getSiblings(node).forEach(function(elem) {
elem.classList.add(className);
});
}
// Get Children
// It is a simple function to get all child from parent
// Feel free to use it like a Pro
function getChildren(node) {
var childNodes, children;
childNodes = node.childNodes;
children = [];
for (var i=0, len=childNodes.length; i<len; i++ ) {
if (childNodes[i].nodeType == 1) {
children.push(childNodes[i]);
}
}
return children;
}
function addClassToChildren(node, className) {
getChildren(node).forEach(function(elem) {
elem.classList.add(className);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment