The designer want to make the company name in blue, but the company name is embed in the text without any html element surrounding it.
I want to be able to find a string an开发者_运维技巧d set only that string to blue
I've got this code, but it makes the whole text in blue
$(function() {
$('div:contains("The Company Name")').css("color","blue");
});
this is sample code
<div>The company name is great and makes a lot of happy customers</div>
<div>You can have more info on <a href="link">The company name</a>[...]</div>
This the result I want
<div><span style="color:blue;">The company name</span> is great and makes a lot of happy customers</div>
<div>You can have more info on <a href="link"><span style="color:blue;">The company name</span></a>[...]</div>
Anyone?
$(function() {
$('div').each(function() {
$(this).html($(this).html().toString().replace('The Company Name', '<span style="color: blue">The Company Name</span>'));
});
});
Could do it like this as well, if you wish to create the span
using jQuery instead of just straight off writing <span style="color:blue;">etc...
:
var s = "The company name";
$('div:contains("'+s+'")').html(function(i,e){
var p = new RegExp(s,"g");
return e.replace(p,$('<span />').css('color','blue').text(s).wrap('<div />').parent().html());
});
example: http://jsfiddle.net/niklasvh/Mytzh/
You can use the jQuery highlight plugin to accomplish your goal.
精彩评论