Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

css - Find text string in jQuery and make it bold

What I want to do is use jQuery to find a piece of text within a paragraph and add some CSS to make it bold. I can't seem to figure out why this won't work:

$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});

The text in "about_theresidency" is dynamically pulled in, hence me executing it after the window has loaded.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use replace() with html():

var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));

Edit: http://jsbin.com/AvUcElo/1/edit

I turned it into a lil' plugin, here:

$.fn.wrapInTag = function(opts) {

  var tag = opts.tag || 'strong'
    , words = opts.words || []
    , regex = RegExp(words.join('|'), 'gi') // case insensitive
    , replacement = '<'+ tag +'>$&</'+ tag +'>';

  return this.html(function() {
    return $(this).text().replace(regex, replacement);
  });
};

// Usage
$('p').wrapInTag({
  tag: 'em',
  words: ['world', 'red']
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...