How to replace text nodes in HTML to HTML nodes like the question in stackoverflow: “jQuery way” to replace just a text node with a mix of HTML and text?
Created
June 3, 2015 08:03
-
-
Save gunyarakun/6e4072ba0b1b38ef2e54 to your computer and use it in GitHub Desktop.
Replace text nodes in HTML to HTML nodes
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 jsdom = require('jsdom'); | |
var escapeHTML = function(str) { | |
return str.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">"); | |
}; | |
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