PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

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

 October 15, 2022     css, dom, dom-events, html, javascript     No comments   

Issue

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?


Solution

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;
    });
}


Answered By - bodkia22
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing