I have the HTML div block and a CSS class. I also have another CSS class. I want to change or add the class on the button click in jQuery.
Like, I have a my_class and a second one new_class. I want to change my_class to new_class on the button click. Is there any method to add a new class to the div block on button click in Jquery?
<!DOCTYPE html>
<html>
<head>
<title>How to add a new class to the div block in jQuery?</title>
<style type="text/css">
.my_class{
background: green;
}
.new_class{
background: red;
}
</style>
</head>
<body>
<div class="my_class">This is div block</div>
<button class="btn">Submit</button>
</body>
</html>
As you can see in the above code, I have two CSS classes. The first class is already applied on div but I want to add a new class using jQuery. How can I add a new class to the div on button click in jQuery?
Changing a div class is the same look as adding a new class to a div block. The answer is hidden in the first sentence. You have to add a new class to div on the button click. You can use the jQuery addClass() function to change or add a class to the div block on a button click or in another process. If you want to add a CSS class to the div block then you should use the addClass() function. If you create a div block without any CSS class and you want to add a class while executing jQuery scripts on the button click then you can use the jQuery addClass() function.
Let's change the div class using jQuery.
<!DOCTYPE html>
<html>
<head>
<title>Add New class to div block using jQuery</title>
<style type="text/css">
.my_class{
background: green;
}
.new_class{
background: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#btn_id" ).click(function() {
$("#div_id").addClass('new_class');
});
});
</script>
</head>
<body>
<div class="my_class" id="div_id">This is div block</div>
<button class="btn" id="btn_id">Submit</button>
</body>
</html>
Execute the above code. In the above code, the div class is my_class and you can see we have another class new_class. We create an on-click function using the button id and change the div class using the div id and jQuery addClass() function. In this way, you can change or add a new class to div using the jQuery library.
Use the jQuery addClass() method to add a new class or change a class using the jQuery library.
The syntax of addClass() method -
$("id of div").addClass("new_class");
Use id of a div block and addClass() method to change div class.
If you want to add a new class on the button click -
script type="text/javascript">
$(document).ready(function() {
$( "#my_btn" ).click(function() {
$("#my_div_id").addClass('class_two');
});
});
</script>
HTML button and div like that -
<div class="class_one" id="my_div_id">Add new class</div>
<button class="btn" id="my_btn">Click Me</button>
Create two classes class_one and class_two in the stylesheet.
