Home > Web Front-end > CSS Tutorial > How Can I Efficiently Bold Specific Text Strings within Dynamically Loaded Content Using jQuery?

How Can I Efficiently Bold Specific Text Strings within Dynamically Loaded Content Using jQuery?

Patricia Arquette
Release: 2024-11-24 18:53:14
Original
1057 people have browsed it

How Can I Efficiently Bold Specific Text Strings within Dynamically Loaded Content Using jQuery?

Finding and Bolding Text Strings with jQuery

Finding a specific text string within an element and modifying its appearance is a common task when working with dynamic content. In jQuery, achieving this can be done efficiently. However, if your initial approach isn't yielding the desired results, let's troubleshoot and find a solution.

The code snippet you provided aims to bold text containing the string "cross genre" within an element with the ID "about_theresidency." While the intention is clear, there's a small error in its implementation:

$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
Copy after login

The issue lies in the ":contains" selector, which doesn't work well when the text is dynamically loaded as you have described. To effectively target the desired text, we can use the replace() function in conjunction with html():

var html = $('p').html();
$('p').html(html.replace(/cross genre/gi, '<strong>$&</strong>'));
Copy after login

This code replaces the "cross genre" text with a strong tag version, effectively bolding it.

Alternatively, you can also create a custom plugin to encapsulate this functionality:

$.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']
});
Copy after login

With this plugin, you can now use the wrapInTag() method to wrap specified words in the desired tag, e.g., 'em' for emphasis or 'strong' for bold.

By incorporating these fixes, you can efficiently find and modify text strings in your jQuery code, ensuring dynamic content is presented with the desired styling.

The above is the detailed content of How Can I Efficiently Bold Specific Text Strings within Dynamically Loaded Content Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template