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>
function turnRed() {
var myPara = document.getElementById("changeText");
myPara.innerHTML = myPara.innerHTML.replace(/\bboy\b(?!<)/g, '<span style="color:blue">boy</span>');
}
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.