Add css style to a specific text using jquery

Issue

How to add style to a particular text or characters within a div?

<div class="test">blocks of texts here.</div>

I want to add color to the word “texts” without using any tags such as span to enclose it. Thanks in advance.

Solution

You can’t do that without wrapping the text to an element. But you can do the wrapping with jQuery:

var $test = $('.test').html();
$test = $test.replace(/texts/gi, '<span class="tomato">texts</span>');
$('.test').html($test);

http://jsfiddle.net/r36xjzs7/

This will recreate the whole element though, so it’s not that efficient.

Answered By – balzafin

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.