jQuery has various methods such as addClass(), removeClass() etc. which are used to manipulate the CSS classes that are assigned to HTML elements.
The addClass() method is used to add one or more classes to the selected HTML element.
Example of Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".jQuery-example-addclass-button").click(function(){
$(".jQuery-example-addclass-bold-text").addClass("jQuery-example-addclass-paragraph");
});
});
</script>
<style>
.jQuery-example-addclass-paragraph {
color: red;
}
</style>
<p>This <b class="jQuery-example-addclass-bold-text">bold</b> text has red color</p>
<button class="jQuery-example-addclass-button">Click here to add red class to paragaph element</button>
Output
This bold text has red color
The removeClass() method is used to removes one or more classes from the selected HTML element.
Example of Code
<script>
$(document).ready(function(){
$(".jQuery-example-removeclass-button").click(function(){
$("#jQuery-example-removeclass-paragraph-id").removeClass("jQuery-example-removeclass-paragraph");
});
});
</script>
<style>
.jQuery-example-removeclass-paragraph {
color: red;
}
</style>
<p>This <b class="jQuery-example-removeclass-paragraph" id="jQuery-example-removeclass-paragraph-id">bold</b> text has red
color</p>
<button class="jQuery-example-removeclass-button">Click here to remove red class from paragaph element</button>
Output
This bold text has redcolor
The toggleClass() method is used to toggles between adding/removing classes from the selected HTML element.
Example of Code
<script>
$(document).ready(function(){
$(".jQuery-example-toggleClass-button").click(function(){
$("#jQuery-example-toggleClass-paragraph-id").toggleClass("jQuery-example-toggleClass-paragraph");
});
});
</script>
<style>
.jQuery-example-toggleClass-paragraph {
color: red;
}
</style>
<p>This <b class="jQuery-example-toggleClass-paragraph" id="jQuery-example-toggleClass-paragraph-id">bold</b> text has red
color</p>
<button class="jQuery-example-toggleClass-button">Click here to add and remove red class from paragaph element</button>
Output
This bold text has redcolor
The css() method is used to set or return the style attribute.
Example of Code
<script>
$(document).ready(function(){
$(".jQuery-example-css-button").click(function(){
$("abbr").css("color", "red");
});
});
</script>
<p>This <abbr title="Hypertext Markup Language" class="jQuery-example-Css-method-abbr">HTML</abbr> text has red color</p>
<button class="jQuery-example-css-button">Click to add red class to paragaph element using CSS method</button>
Output
This HTML text has red color
