Alex Cardo
Alex Cardo

Reputation: 365

Get value of string; find this string in content; apply new style to this string thanks to jQuery

The answer seems to be simple, but I can't find the solution.

I have a WordPress site. In my right column, I print some meta data. I want to get the text value of some data, then find it in my .entry-content, and apply the new style to this exact string. I can cope with this task by applying the new style to the entire content inside.entry-content, but I can't apply it with a single string (which is in numerous places in the text).

Here is my code below:

jQuery(document).ready(function($) {

var str = $('.rrname').text(); // I've got the value
$(".entry-content:contains('"+ str +"')").css( "text-decoration", 
"underline"); // all the content in the div .entry-content now underline

});

For instance I have a string with the show name:

Show name: "The Good Doctor"

In my article, this phrase appears numerous times. I want that each time, The Good Doctor to be underline in my entire article inside the div .entry-content.

I've tried this code with no results too:

jQuery(document).ready(function($) {

var str = $('.rrname').text();
$(".entry-content:contains('"+ str +"')").each(function() {
    $(this).text().css( "text-decoration", "underline");
});


});

Thanks for the assistance!

Upvotes: 1

Views: 710

Answers (2)

git-e-up
git-e-up

Reputation: 904

var str = $('.rrname').text();

$(".entry-content").text(function () {
     $(".entry-content").html($(this).text().replace(str, '<span class="underline">'+str+'</span>')); 
});

Remove any extra spaces between html tags in .rrname. http://jsfiddle.net/ozyLxgwp/30/

Upvotes: 0

Taplar
Taplar

Reputation: 24965

//dummy pull of an element containing text to match against
var $div = $('div');
//dummy variable containing what to search for to replace
var underlineMe = 'The Good Doctor';
//replace all occurances of our search string with a wrapped version
var modifiedValue = $div.html().replace(new RegExp(underlineMe, 'g'), '<span class="underline">'+ underlineMe +'</span>');

//update the value in the DOM
$div.html(modifiedValue);
.underline {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Blah Blah Blah, I am text that contains The Good Doctor, and I want it to be underlined.  Oh, and The Good Doctor might appear multiple times.
</div>

Upvotes: 1

Related Questions