Skip to content
Advertisement

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

Advertisement

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>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement