-1

I am trying to change the color of a word. In other words, if I have "boy girl boy girl" I want "boy" to have text color blue.

<html>
    <head>
    <title>color</title>
        <script language="javascript">
            function turnRed() {
                var myPara = document.getElementById("changeText");
                if(myPara=="boy"){
                    myPara.style.color = "blue";
                }
            }
        </script>
    </head>
    <body>
        <p id="changeText">boy girl boy girl boy girl boy girl boy girl boy girl</p>
        <p1><button onclick='turnRed()'>Turn Red</button></p1>
    </body>
 </html>
2
  • Hint: you need to separate boy into another container in order to change it's color without changing girl's.
    – loki
    May 22, 2012 at 3:06
  • i just want to change color of a string containing "boy"
    – toky
    May 22, 2012 at 3:30

2 Answers 2

5
function turnRed() {
  var myPara = document.getElementById("changeText");
  myPara.innerHTML = myPara.innerHTML.replace(/\bboy\b(?!<)/g, '<span style="color:blue">boy</span>');
}
3
  • This will add the span tags every time the button is clicked, e.g. if the button is clicked 3 times, it will be <span color="blue"><span color="blue"><span color="blue">boy</span></span></span>. Also, using a class as suggested in ark3typ3's answer below is a better solution than hardcoding style information into your code. May 22, 2012 at 3:06
  • 1
    @toky we need more info about your code, upload it to jsfiddle.net so we can help you. I think the problem is in the line document.getElementById("changeText"); may be it is not rendering the changeText element at the moment the script loads.
    – loki
    May 22, 2012 at 3:22
  • @toky, seems I'm a little distracted here. solution is updated (jsfiddle.net/S4uPD).
    – xiaoyi
    May 22, 2012 at 3:35
1

I'd recommend creating a class in your css then adding it to the element and removing it as necessary. Look into jQuery ( http://www.jquery.com ) as it does most of the grunt work of javascript for you and allows you to develop large scale applications fast. Plus the documentation is quite good.

<style type="text/css">
    .color1 { color: blue; }
</style>

to add it

document.getElementById('changeText').classList.add('color1');

to remove it

document.getElementById('changeText').classList.remove('color1');
1
  • Using classes is a good solution, but this answer doesn't address the OPs requirement of how to apply it only to specific words. May 22, 2012 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.