Skip to content

Instantly share code, notes, and snippets.

@kevinkace
Created June 9, 2016 18:42
Show Gist options
  • Select an option

  • Save kevinkace/411d2063f3442393a376bbc9975ffd7d to your computer and use it in GitHub Desktop.

Select an option

Save kevinkace/411d2063f3442393a376bbc9975ffd7d to your computer and use it in GitHub Desktop.
posthtml recursive tree walker to add first-child/last-child classes to all elements
var iteration = 0,
maxIterations = 200;
function addClass(node, className) {
var classNameRegex = new RegExp(className, "g");
node.attrs = node.attrs || {};
if(!node.attrs.class || !classNameRegex.test(node.attrs.class)) {
node.attrs.class = node.attrs.class ? node.attrs.class + " " + className : className;
}
}
function removeClass(node, className) {
var classNameRegex = new RegExp(className, "g");
node.attrs = node.attrs || {};
if(node.attrs.class || classNameRegex.test(node.attrs.class)) {
node.attrs.class = node.attrs.class.replace(classNameRegex, "");
}
}
function walker(node) {
var firstNode = false,
prevNode = false;
++iteration;
if(iteration > maxIterations) {
console.log("ERR! exceeded max iterations");
return node;
}
if(!node.tag || !node.content.length) {
return node;
}
node.content.forEach((child) => {
if(child.tag) {
if(!firstNode) {
firstNode = true;
child.attrs = child.attrs || {};
addClass(child, "first-child");
}
if(prevNode) {
removeClass(prevNode, "last-child");
}
addClass(child, "last-child");
prevNode = child;
}
if(child.content) {
child = walker(child);
}
});
return node;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment