Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap Each * on a Page Using jQuery

I need to wrap each asterisks on a page with <span class="red"></span>. The few things I've tried don't work. I think what this boils down to is that I need to search the page for a specific character, and I can't figure out how to do that.

like image 602
JacobTheDev Avatar asked Dec 15 '22 11:12

JacobTheDev


1 Answers

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/

like image 148
VisioN Avatar answered Dec 28 '22 22:12

VisioN