Last active
July 6, 2021 02:29
-
-
Save alexmacarthur/1b3d5ce219e6db58298afee5cdbfc5c2 to your computer and use it in GitHub Desktop.
Expand Text Nodes - Split HTML Text Content into Individual Text Nodes for Each Character
This file contains 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
// Unless the characters are individually inserted, the text content of HTML is grouped together in | |
// only as many text nodes are necessary to contain it. For example, the following markup will have only two text nodes: | |
// | |
// <span>first text node!<strong>second text node!</strong></span> | |
// | |
// Sometimes, however, you might want each character of text to exist as SEPARATE text nodes. This will do that. As a | |
// result, the afforementioned markup will contain 33 text nodes, rather than only two. | |
const expandTextNodes = (element) => { | |
[...element.childNodes].forEach((child) => { | |
if (child.nodeValue) { | |
child.nodeValue.split("").forEach((c) => { | |
child.parentNode.insertBefore(document.createTextNode(c), child); | |
}); | |
child.remove(); | |
return; | |
} | |
expandTextNodes(child); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment