开发者

Jquery contains text and make it blue

开发者 https://www.devze.com 2023-03-13 14:24 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消