Skip to content
Advertisement

How to add style for specific words at HTML using JavaScript?

Could someone help me to write JS function which will take a string(word) as an argument? And then add an additional style (change color for example) for all these words in the HTML. I don’t know where it is located. This “word” can be inside <div>, or <p> or even <b>.

Example:

HTML:

<p id="p1">Hello World!</p>
<div>Hello World!</div>

function Change(string word){
  //change font color to red
}

Call function:

Change("Hello")

Result:

All of the “Hello” words in the HTML have red font color.

By the way, is it possible to write something like this?

Advertisement

Answer

This is the best solution. It works fine at any html, just call matchText("text","black","red");

function replaceInElement(element, find, replace) {
    for (let i= element.childNodes.length; i-->0;) { 
        let child= element.childNodes[i];
        
        if (child.nodeType==1) { 
            let tag= child.nodeName.toLowerCase();  
            if (tag!='style' && tag!='script') 
                replaceInElement(child, find, replace); 
        } else if (child.nodeType==3) { 
            replaceInText(child, find, replace);
        }
    }
}
function replaceInText(text, find, replace) {
    let match; 
    let matches= [];
    
    while (match= find.exec(text.data)){ 
        matches.push(match);
    }
    
    console.log(matches);
    for (let i= matches.length; i-->0;) {
        match = matches[i];

        text.splitText(match.index); 
        text.nextSibling.splitText(match[0].length);

        text.parentNode.replaceChild(replace(match), text.nextSibling); 
    }
}

let matchText = (word, backColor, textColor) => {
    let regexp = new RegExp(`\b(${word})\b`, 'gmi');

    replaceInElement(document.body, regexp, function(match) { 

        var elem= document.createElement('span'); 
        elem.style.backgroundColor = backColor;
        elem.style.color = textColor;

        elem.appendChild(document.createTextNode(match[0]));
        return elem;
    });
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement