html - JavaScript changing text color - Stack Overflow

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

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>

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>
Share Improve this question edited May 22, 2012 at 3:10 kba 19.5k6 gold badges64 silver badges90 bronze badges asked May 22, 2012 at 2:58 toky toky 1191 gold badge5 silver badges15 bronze badges 2
  • Hint: you need to separate boy into another container in order to change it's color without changing girl's. – loki Commented May 22, 2012 at 3:06
  • i just want to change color of a string containing "boy" – toky Commented May 22, 2012 at 3:30
Add a ment  | 

2 Answers 2

Reset to default 5
function turnRed() {
  var myPara = document.getElementById("changeText");
  myPara.innerHTML = myPara.innerHTML.replace(/\bboy\b(?!<)/g, '<span style="color:blue">boy</span>');
}

I'd remend creating a class in your css then adding it to the element and removing it as necessary. Look into jQuery ( http://www.jquery. ) 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');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745175607a4615175.html

相关推荐

  • html - JavaScript changing text color - Stack Overflow

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

    5小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信