Skip to content Skip to sidebar Skip to footer

Document.body.innerHTML Killing Events Need Alternate Solution

Im using the following code to scan the page for matching words and convert the words into a link. var linkWord = function(obj){ for(i in obj){ var x = document.body.innerH

Solution 1:

https://jsfiddle.net/91zux4ar/10/

This was a lot of research and work.. but it was worth the result. I think I'll publish it as jquery plugin

function wordToLinks(words) {
   function getAllTextNodes(ele) {
    var blackListedElements = ["a", "address", "area", "audio", "base", "br", "button", "canvas", "code", "data", "datalist", "embed", "fieldset", "form", "head", "hr", "html", "iframe", "img", "input", "ins", "keygen", "label", "link", "map", "math", "menu", "menuitem", "meta", "meter", "nav", "noscript", "object", "optgroup", "option", "output", "param", "pre", "progress", "rtc", "ruby", "samp", "script", "select", "source", "style", "svg", "textarea", "time", "title", "track", "var", "video", "wbr", "applet", "basefont", "dir", "font", "isindex", "noframes"];

    var nodes = [];

    (function recrusive(element) {
        var all_nodes = element.childNodes,
            l = all_nodes.length,
            child;

        for (var i = 0; i < l; i++) {
            child = all_nodes[i];
            if (child.nodeType == 3) {
                nodes.push(child);
            } else if (child.nodeType == 1 && blackListedElements.indexOf((child.tagName).toLowerCase()) < 0) {
                recrusive(child);
            }
        }

    })(ele);
    return nodes.filter(function (e) {
        return (/\w/).test(e.textContent);
    });
}

function createAtag(str, url) {
    var tag = document.createElement('a');
    tag.innerText = str;
    tag.href = url;
    tag.style.display = 'inline';
    return tag;
}

function getIndex(node, word) {
    //return node.nodeValue.toLowerCase().indexOf(word.toLowerCase());
    var reg = RegExp("\\b(" + word + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig");
    var result = reg.exec(node.nodeValue);
    var index = (result != undefined) ? result.index : -1;
    return index;
}

var all_nodes = getAllTextNodes(document.body);
var w = Object.keys(words);


all_nodes.forEach(function (node) {
    w.forEach(function (word) {
        var c_node = node,
            reg = new RegExp(word, 'i'),
            tag, i;

        i = getIndex(c_node, word);

        while (i > -1) {
            var second = c_node.splitText(i);
            c_node = second.splitText(word.length);
            tag = createAtag(second.nodeValue, words[word])
            second.parentElement.replaceChild(tag, second);
            i = getIndex(c_node, word);
        }
    });
});

}


var words = {
    'the': 'http://www.example.com',
        'Vokalia': 'http://icant.co.uk',
        'behind': 'http://google.com',
};

wordToLinks(words);

Post a Comment for "Document.body.innerHTML Killing Events Need Alternate Solution"