Created
June 9, 2016 18:42
-
-
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
This file contains hidden or 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
| 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