How to underline particular word using jQuery

Today, I got into a situation where I need to underline a particular word anywhere in one of my div element. One way is to find the element manually and apply the CSS. But there were many occurrences of the word. So I thought of doing with jQuery and in couple of minutes, I was able to do it successfully. I am sharing the solution with you to underline particular word using jQuery.

jQuery Code:

For demo purpose, I am underlining the word "jQuery" from the content of the div.

?$(document).ready(function(){
  var dvWords = $("#dvContent").html().split(' ');    
  var dvHTML = ''
  for (i = 0; i < dvWords.length; i++) 
  {   
     if (dvWords[i].toLowerCase() == 'jquery') 
     {
        dvHTML += ' ' + '' + dvWords[i] + '';
     }
     else
     {
         dvHTML += ' ' + dvWords[i];           
     }
   }    
   $("#dvContent").html(dvHTML);
});?

The above code first split the HTML part of the div and creates an array. After that, a loop runs and within the loop code checks for the occurrences of the word "jquery" and if it finds then it surrounds the word in span tag, otherwise add the word into a variable called "dvHTML". When the loop finishes then it assign the new HTML, which is in variable "dvHTML" to the div.

Below is the CSS class used for span tag which allows to underline the word as I have wrapped the word in span tag.

#dvContent span
{
   text-decoration: underline;
   font-weight : bold;
   color : Blue;       
}

See result below:

(Note: You can also see the jQuery code, HTML code and CSS by clicking on the buttons given below.)

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...