In this tutorial we will learn how to Highlight Text in Div with jQuery. jQuery addClass() method and click() method can be used along with simple CSS to highlight the div text on click.
Table of Contents
jQuery addClass() Method
jQuery addClass() Method adds the CSS class to the selected HTML element.
In this example addClass() method is used to add the class to the div which will highlight it's text.
jQuery click() Method
jQuery click() Method binds the click event with the HTML element or it triggers the click event for the selected HTML element.
In this example click() Method is used to execute a function which is going to highlight the text of div.
HTML Code
HTML Code is given below, in this code we have a main div with dummy text inside and a button tag.
CSS is also used to define a class to change the background color of the div which will highlight the text.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Highlight Text in Div</title>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<style>
.highlight
{
background-color: yellow;
}
#div
{
padding: 5px;
}
</style>
</head>
<body>
<div id="div">Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining
essentially unchanged. It was popularized in the 1960s with the release of Letterset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing software like
Aldus PageMaker including versions of Lorem Ipsum.
</div>
<button id="btn">Highlight</button>
<script src="script.js"></script>
</body>
</html>
JQuery Code
JQuery Code is given below, the code is executed whenever button is clicked. This is done using jQuery click() method.
Then addClass() method is used to add the class named highlight to the div.
<script>
$(document).ready(function(){
$('#btn').click(function(){
$('#div').addClass('highlight');
});
});
</script>
Demo
Video Tutorial
Watch video tutorial on How To Highlight Text in Div using jQuery.