Skip to content

Instantly share code, notes, and snippets.

@gunyarakun
Created June 3, 2015 08:03
Show Gist options
  • Save gunyarakun/6e4072ba0b1b38ef2e54 to your computer and use it in GitHub Desktop.
Save gunyarakun/6e4072ba0b1b38ef2e54 to your computer and use it in GitHub Desktop.
Replace text nodes in HTML to HTML nodes
var jsdom = require('jsdom');
var escapeHTML = function(str) {
return str.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
};
var e = jsdom.env('<div class="container"><span>text 1</span><span><br>text2<hr>text3</span></div>', ['http://code.jquery.com/jquery.js'], function (errors, window) {
var $ = window.$;
$('.container > span').contents().filter(function(){return this.nodeType === 3;}).each(
function () {
var e = $(this);
e.replaceWith('<b>' + e.text() + '</b>');
}
);
var resultHTML = $('.container').first().html();
if (resultHTML === '<span><b>text 1</b></span><span><br><b>text2</b><hr><b>text3</b></span>') {
console.log('Yay!: %s', resultHTML);
} else {
console.log('Failed: %s', resultHTML);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment