Search code examples
javascriptjqueryhtmlregexgoogle-chrome-extension

Replace Text Node with HTML span content


I should write an extension that can change a color for a word in web page, this code can replace words but can't change their background color

See below code : content.js

walk(document.body);

function walk(node)  
{

    var child, next;

    switch ( node.nodeType )  
    {
        case 1: 
        case 9:  
        case 11: 
            child = node.firstChild;
            while ( child ) 
            {
                next = child.nextSibling; 
                walk(child);
                child = next;
            }
            break;

        case 3: 
            handleText(node);
            break;
    }
}

function handleText(textNode) 
{
    var v = textNode.nodeValue;

    v = v.replace(/Apple/gi, '<span class="red">Pineapple</span>');

    textNode.nodeValue = v;
}

Image

How to apply <span class="red"> for pineapple?


Solution

  • If you put HTML into a nodeValue it will be escaped. Try:

    textNode.parentElement.innerHTML = 'This <strong>accepts</strong> HTML';