w3resource

jQuery: Underline all the words of a text

jQuery Practical exercise Part - I : Exercise-16

Underline all the words of a text using jQuery.

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
 <title>Underline all words of a text through jQuery</title>
 </head>
 <body>
 <p>The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises.</p>
 </body>
 </html>

CSS Code :

p span{
    text-decoration: underline;
  }

JavaScript 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>');
			}
		}
	
	});

});

See the Pen jquery-practical-exercise-16 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Using jQuery remove all the options of a select box and then add one option and select it.
Next: How to get the value of a textbox using jQuery.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.