更改html文档中<tag>的颜色

时间:2016-08-28 08:00:02

标签: javascript jquery html css

我正在使用pagedown发布代码。我知道如何更改HTML文档中特定单词的颜色,即使用下面的示例代码

<script>
var text = document.getElementById("wmd-post");
var str = text.innerHTML,
    reg = /if|else|span|/ig; //g is to replace all occurances

//fixing a bit
var toStr = String(reg);
var color = (toStr.replace('\/g', '|')).substring(1);

//split it
var colors = color.split("|");

if (colors.indexOf("if") > -1) {
    str = str.replace(/if/g, '<span style="color:#069;">if</span>');
}

document.getElementById("wmd-post").innerHTML = str;
</script>

我还想知道如何更改<span><div><p>等标签的颜色当我尝试在上面的代码中添加它们时,它将无法正常工作

var text = document.getElementById("wmd-post");
var str = text.innerHTML,
    reg = /<span>|</div>|/ig; //g is to replace all occurances

//fixing a bit
var toStr = String(reg);
var color = (toStr.replace('\/g', '|')).substring(1);

//split it
var colors = color.split("|");

if (colors.indexOf("<span>") > -1) {
    str = str.replace(/<span>/g, '<span style="color:#069;"><span></span>');
}

document.getElementById("wmd-post").innerHTML = str;

我应该使用什么方法

1 个答案:

答案 0 :(得分:0)

找出一种方法

<div id="wmd-post">
  
  Some other words
  <p>&lt;span&gt;</p>
  <p>&lt;/span&gt;</p>
   Some more words 
  
</div>  
<script>
var text = document.getElementById("wmd-post");
var str = text.innerHTML,
    
str = str.replace(/&lt;\/span&gt;/g, '<span style="color:red">&lt;/span&gt;</span>');
str = str.replace(/&lt;span&gt;/g, '<span style="color:red">&lt;span&gt;</span>');

document.getElementById("wmd-post").innerHTML = str;
</script>