Home >Web Front-end >CSS Tutorial >How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?
Bolding Text Strings in jQuery
You are seeking a jQuery solution to highlight a specific text string within a paragraph by bolding it. However, your code is not producing the desired result:
$(window).load(function() { // ADD BOLD ELEMENTS $('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'}); });
This code aims to target the text with the phrase "cross genre" within the element with the ID "about_theresidency" and apply the CSS property "font-weight" to make it bold. However, it remains ineffective.
Solution
To bold text strings using jQuery, you can employ the replace() method along with html(). The following code demonstrates how:
var html = $('p').html(); $('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
This code snippet:
Additional Tip
The code can be refined into a plugin:
$.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'] });
This plugin allows you to wrap specific words in HTML tags. In the example provided, it wraps the words "world" and "red" in tags.
The above is the detailed content of How Can I Bold Specific Text Strings Within a Paragraph Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!