Skip to content
Related Articles

Related Articles

Improve Article

How to underline all words of a text using jQuery ?

  • Last Updated : 30 Nov, 2020

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

Attention reader! Don’t stop learning now. Get hold of all the important Comcompetitivepetitve Programming concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :