Last active
January 14, 2018 10:55
-
-
Save gadzhimari/10aefc1e184489ff2fea67fec7a9236d to your computer and use it in GitHub Desktop.
Tree Walker
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
/* Replace all text nodes which has parent div element to wrapped by p tag. | |
Example | |
Before | |
<body> | |
<p>Boom</p> | |
text | |
<div>Bam</div> | |
</body> | |
After | |
<body> | |
<p>Boom</p> | |
text | |
<div><p>Bam</p></div> | |
</body> | |
*/ | |
export default (document) => { | |
const filter = node => | |
node.parentElement.tagName === 'DIV' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; | |
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, filter); | |
while (walker.nextNode()) { | |
const node = walker.currentNode(); | |
const pEl = document.createElement('p'); | |
node.replaceWith(pEl); | |
pEl.append(node); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment