Skip to content

change color of words within an array

if i have an javascript array of words

var keywords = ["select","from","where","mars"];

and HTML element holding a text

<div id="mytext">Hello from planet mars</div>

How to use javascript to color in orange any word found in this element mytext of words list in the array keywords !

enter image description here

Answer

        <html>
        <head></head>
        <body>
        <div id="mytext">Hello from planet mars</div>
            <script>
                var keywords = ["select","from","where","mars"];
                mytext=document.getElementById("mytext");
                len=keywords.length;
                for(i=0;i<len;i++){
                    mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
                }
                
            </script>
        <body>

You can use this code and replace the orange color with the color you want

var keywords = ["select","from","where","mars"];
                mytext=document.getElementById("mytext");
                len=keywords.length;
                for(i=0;i<len;i++){
                    mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],"<span style='color:orange;'>"+ keywords[i] +"</span>");
                }
<html>
        <head></head>
        <body>
        <div id="mytext">Hello from planet mars</div>
            
        <body>
 </html>