SO - 29535939
by Arun P Johny
HTML
<div>
some content
<div>another content</div>
</div>
content in body
JavaScript
//the main point here is you need to replace only the contents of the text node, not all the html parts
jQuery('*').contents().each(function () {
//not a text node or there is no content to replace
if (this.nodeType != 3 || !this.nodeValue.trim()) {
return;
}
//replace the value of the text node
$(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
return '<span style="color: green;">' + part.split("").reverse().join("") + '</span>'
}))
});