I need to wrap each asterisks on a page with . The few things I\'ve tried don\'t work. I think what this boils down to is
This is a bit dirty and risky (explained below), but you could try the following:
var allHTML = $("body").html();
allHTML = allHTML.replace(/\*/g, "<span class=\"red\">*</span>");
$("body").html(allHTML);
http://jsfiddle.net/6rDK4/
Note: As Dogbert pointed out this might replace *
characters that are within HTML tags, e.g. node attributes.
EDIT: Bear in mind that this might reattach all the scripts you have in your body though! Try replacing body
with your main container.
EDIT2: VisioN posted a more elaborate but a lot safer solution.
This will work and not replace * in tags it shouldn't.
http://jsfiddle.net/DR6Ca/2/
var text = $("body").find(":contains(*)").contents().filter(function() {
//Don't include css or script tags, all other text nodes are fine.
return this.nodeType == 3
&& ($(this).parent().get(0).tagName.toUpperCase() !== "SCRIPT")
&& ($(this).parent().get(0).tagName.toUpperCase() !== "STYLE");
}).replaceWith(function() {
return this.textContent.replace(/\*/g, "<span class=\"red\">*</span>");
You can test the others code in this jsfiddle to see if they keep the "hi" blue or not. If it doesn't stay blue they have a bug.
Without using jQuery so it might be a little faster, and definitely not dependent on libs:
(function(str,e){
var regex = new RegExp(str, 'gi');
e.innerHTML = e.innerHTML.replace(regex, '<span class="red">*</span>');
})('*',document.body);
How about this?...
http://jsfiddle.net/n3Sqn/
$("body:contains(*)").contents().each(function() {
if(this.nodeType == 1)
{
$(this).html($(this).html().replace(/\*/g, "<span class=\"red\">*</span>"))
}
});
For not replacing the entire HTML (really bad attitude), we can do fast manipulation with elements:
var specialTags = ["script", "style"].join("|"),
re = new RegExp("^(?:" + specialTags + ")$", "i");
for (var els = document.getElementsByTagName("*"), i = els.length; i--;) {
var el = els[i];
if (re.test(el.tagName))
continue;
for (var j = 0, childs = el.childNodes, lj = childs.length; j < lj; j++) {
var child = childs[j];
if (child.nodeType === 3 && child.nodeValue.indexOf("*") > -1) {
var segments = child.nodeValue.split("*");
for (var k = 0, lk = segments.length; k < lk; k++) {
el.insertBefore(document.createTextNode(segments[k]), child);
if (k < lk - 1) {
var span = document.createElement("span");
span.className = "red";
span.appendChild(document.createTextNode("*"));
el.insertBefore(span, child);
}
}
el.removeChild(child);
}
}
}
This is pure JavaScript which does not require jQuery, that can't really help here.
DEMO: http://jsfiddle.net/T4ZXA/5/