如何将颜色更改为div内的html单词

时间:2017-09-04 14:50:47

标签: javascript html html5 colors

我需要更改div中单词的颜色。它充满了恐惧,有一个javascript函数可以在DB上读取并通过我的div的ID写入。 我试图给单词INFO(只有INFO)上色,但没有成功:

$("div:contains('INFO')").each(function () {
    $(this).html($(this).html().replace("INFO", "<span class='green'>INFO</span>"));
});


/* THis is only an example*/

document.getElementById('textLog').innerHTML ="Load[DB]: INFO";
.green {
	color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="menuLog">
		<div class="log">
			<h3 class="textStyle">Log</h3>
			<div id="textLog" class="silverStyle" name="textLog" required></div><br>
		</div>
	</div>

3 个答案:

答案 0 :(得分:3)

您可以抓取包含所需文本的元素,就像您已经尝试过的那样,然后使用html替换单词INFO:

$('div:contains("INFO")').html(function () {
    return $(this).html().replace(/INFO/g, "<span style='color: green'>INFO</span>"); 
});

根据评论中的所有额外要求更新了小提琴:https://jsfiddle.net/bL24mw97/

答案 1 :(得分:1)

试试这个。

function changeColor() {
  $( "span:contains('Info')" ).css( "color", "green" );
}

document.getElementById('textLog').innerHTML = "<span>Info<span>";
document.getElementById('textLog1').innerHTML = "<span>Info<span>";
document.getElementById('textLog2').innerHTML = "<span>Info<span>";

//This part emulates the data loading
//setTimeout(function(){ 
//  console.log('Data populated....');
//  //when finished you must call the function
//  changeColor();
//; }, 500);

changeColor();
.green {
	color: green;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>contains demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div id="textLog" class="silverStyle" name="textLog" required></div>
<div>TEST</div>
<div id="textLog1" class="silverStyle" name="textLog" required></div>
<div id="textLog2" class="silverStyle" name="textLog" required></div>

</body>
</html>

您需要调用changeColor()方法来更改颜色,在填充信息的函数完成时执行此操作。

答案 2 :(得分:-2)

我读了你所有的帮助,但有人不满意我的问题,有人去了 接近解决它,但问题总是一样的,你的例子 只有一个字,所以我更改了reg exp:

$('#textLog').html('INFO start <br> INFO loadDB <br> WARN connection <br> ERROR DB not exist');
changeColor();


function changeColor() {
	$('div:contains("INFO")').html(function () {
	    return $(this).html().replace(/INFO/g, "<span       style='color:green'>INFO</span>"); 
	  });
    	$('div:contains("WARN")').html(function () {
	    return $(this).html().replace(/WARN/g, "<span       style='color:orange'>WARN</span>"); 
	  });
    	$('div:contains("ERROR")').html(function () {
	    return $(this).html().replace(/ERROR/g, "<b><span       style='color:red'>ERROR</span></b>"); 
	  });
    
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textLog" class="silverStyle" name="textLog" required></div><br>