In this code snippet you will learn how to add class and remove class for HTML div elements using JQuery scripting.
The following is the HTML code I used for this code snippet.
HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="div1">Name 1</div>
<div class="div2">Name 2</div>
<div class="div3">Name 3</div>
<div class="div4">Name 4</div>
</body>
</html>The following is the CSS code I used for this code snippet.
CSS
<style>
.active {
border-style: solid;
border-width: 1px;
border-color: black;
}
</style>The following is the JQuery scripting I used for this code snippet.
JQuery
<script>
$(document).ready(function() {
$('div').on('click', function() {
$('div').removeClass('active');
$(this).addClass('active');
});
});
</script>Complete code
<!DOCTYPE html>
<html>
<head>
<style>
.active {
border-style: solid;
border-width: 1px;
border-color: black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('div').on('click', function() {
$('div').removeClass('active');
$(this).addClass('active');
});
});
</script>
</head>
<body>
<div class="div1">Name 1</div>
<div class="div2">Name 2</div>
<div class="div3">Name 3</div>
<div class="div4">Name 4</div>
</body>
</html>Output
Conclusion
I hope you liked this code snippet. Thanks for reading please provide your valuable comments.
