Skip to content

Instantly share code, notes, and snippets.

@gadzhimari
Last active January 14, 2018 10:55
Show Gist options
  • Save gadzhimari/10aefc1e184489ff2fea67fec7a9236d to your computer and use it in GitHub Desktop.
Save gadzhimari/10aefc1e184489ff2fea67fec7a9236d to your computer and use it in GitHub Desktop.
Tree Walker
/* 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