Created
September 27, 2018 17:20
-
-
Save gartenfeld/e608dc0f0d988376633e43ab0f1fb2bc to your computer and use it in GitHub Desktop.
Recipe for wrapping dangling text nodes with Cheerio
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
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