Add and Remove Class Using jQuery


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>
<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.

<style>
        .active {  
            border-style: solid;  
            border-width: 1px;  
            border-color: black;  
        }  
    </style>

The following is the JQuery scripting I used for this code snippet.

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

Check Live Demo : Add and Remove Class Using jQuery

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s