Open In App

How to underline all words of a text using jQuery?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To underline all words of a text using jQuery, you can wrap each word in a <span> tag and apply the CSS text-decoration property. This approach allows for individual styling of each word within a text element.

Approach

  • Create a basic structure for the web page. The CSS rule p span text-decoration: underline; is defined as underlining any text within <span> tags inside <p> elements.
  • The jQuery library is included in the <head> section using a script tag to enable jQuery functionality.
  • Inside the <body>, there are two headings and a paragraph containing the text that needs to be underlined.
  • The jQuery script selects each <p> element splits its text content into individual words and wraps each word in a <span> tag.
  • The paragraph's HTML content is then replaced with the new HTML, where each word is wrapped in a <span> tag, resulting in each word being underlined.

Example: The example shows how to underline all words of a text using jQuery.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        p span {
            text-decoration: underline;
        }
    </style>

    <script src="https://releases.jquery.com/git/jquery-git.js">
    </script>
</head>

<body>
    <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>
        $('p').each(function () {

            let 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:

JQueryunderline
Output

Similar Reads