Wrap Each * on a Page Using jQuery

后端 未结 5 1325
挽巷
挽巷 2021-01-06 06:55

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

5条回答
  •  一向
    一向 (楼主)
    2021-01-06 07:51

    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/

提交回复
热议问题