jQuery: Click a word in the paragraph and highlight it
jQuery Fundamental - II : Exercise-67
Click a word in the paragraph and highlight it.
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>Click a word in the paragraph and highlight it.</title>
</head>
<body>
<p>
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
</p>
</body>
</html>
JavaScript Code :
var words = $( "p" ).first().text().split( /\s+/ );
var text = words.join( "</span> <span>" );
$( "p" ).first().html( "<span>" + text + "</span>" );
$( "span" ).on( "click", function() {
$( this ).css( "background-color", "red" );
});
See the Pen jquery-fundamental-exercise-67 by w3resource (@w3resource) on CodePen.
Contribute your code and comments through Disqus.
Previous: Increase the width of a division by specified pixels once it is clicked.
Next: Change the font weight and color of paragraphs on mouseenter and mouseleave.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics