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.
$(window). load(function() { // ADD BOLD ELEMENTS $('#about_theresidency:contains("cross genre")'). css({'font-weight':'bold'}); });
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'] });
I had a similar problem and tried to use the solution proposed by elclanrs. It works great, but only if you have no html elements within the text you want to alter. If there were any tags inside the text, they would have been lost after running the wrapInTag
function.
Here is my inner-node-friendly solution to the problem (I included links to the resources I used to write the code).
// http://stackoverflow.com/a/9795091 $.fn.wrapInTag = function (opts) { // http://stackoverflow.com/a/1646618 function getText(obj) { return obj.textContent ? obj.textContent : obj.innerText; } var tag = opts.tag || 'strong', words = opts.words || [], regex = RegExp(words.join('|'), 'gi'), replacement = '<' + tag + '>$&</' + tag + '>'; // http://stackoverflow.com/a/298758 $(this).contents().each(function () { if (this.nodeType === 3) //Node.TEXT_NODE { // http://stackoverflow.com/a/7698745 $(this).replaceWith(getText(this).replace(regex, replacement)); } else if (!opts.ignoreChildNodes) { $(this).wrapInTag(opts); } }); };
Example: http://jsbin.com/hawog/1/edit
Try:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').each(function(){
$(this).html(
$(this).html().replace(/cross genre/g,'<strong>$&</strong>')
);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With