Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created September 27, 2018 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gartenfeld/e608dc0f0d988376633e43ab0f1fb2bc to your computer and use it in GitHub Desktop.
Save gartenfeld/e608dc0f0d988376633e43ab0f1fb2bc to your computer and use it in GitHub Desktop.
Recipe for wrapping dangling text nodes with Cheerio
var $head = $('.entry h2.orth');
var $placeholder = $('<div></div>');
var nodes = $head[0].children; // Raw children nodes
// Strange enough this is an object!
// To iterate correctly without dropping nodes
// It must be converted to an array
_.toArray(nodes).forEach(child => {
if (child.type === 'text') {
var text = child.data.trim();
// If node is not empty
if (text) {
var $textNode = $('<span></span>')
.addClass('text-node')
.text(text);
$placeholder.append($textNode);
} // Inner if
} else {
$placeholder.append(child);
}
}); // forEach
$head.empty().append($placeholder.html());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment