Open In App

How to underline all words of a text using jQuery ?

Last Updated : 30 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Given a statement and the task is to underline all the text words of HTML page using jQuery. We will use text-decoration property to add underline to each words.

HTML code:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        p span {
            text-decoration: underline;
        }
    </style>
  
    <script src=
    </script>
</head>
  
<body>
    <h2>GeeksForGeeks</h2>
      
    <h2>
        How to underline all the words 
        of a text using jQuery?
    </h2>
  
    <p>
        Geeks For Geeks. A computer 
        science portal for Geeks.
    </p>
</body>
  
</html>


jQuery Code:




$('p').each(function () {
  
    var text_words = $(this).text().split(' ');
  
    $(this).empty().html(function () {
  
        for (i = 0; i < text_words.length; i++) {
            if (i === 0) {
                $(this).append('<span>' 
                + text_words[i] + '</span>');
            } else {
                $(this).append(' <span>' 
                + text_words[i] + '</span>');
            }
        }
    });
});


Final code: The following code is the combination of the above two code snippets.




<!DOCTYPE html>
<html>
  
<head>
    <style>
        p span {
            text-decoration: underline;
        }
    </style>
  
    <script src=
    </script>
</head>
  
<body>
    <h2>GeeksForGeeks</h2>
  
    <h2>
        How to underline all the words 
        of a text using jQuery?
    </h2>
  
    <p>
        Geeks For Geeks. A computer 
        science portal for Geeks.
    </p>
      
    <script>
        $(document).ready(function () {
            $('p').each(function () {
                var text_words = 
                    $(this).text().split(' ');
  
                $(this).empty().html(function () {
                    for (i = 0; i < text_words.length; i++) {
                        if (i === 0) {
                            $(this).append('<span>' 
                            + text_words[i] + '</span>');
                        }
                        else {
                            $(this).append(' <span>' 
                            + text_words[i] + '</span>');
                        }
                    }
                });
            });
        });
    </script>
</body>
  
</html>


Output:

Supported Browsers are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads