jQuery Add and Remove CSS Classes


jQuery CSS Classes Manipulation

jQuery provides several methods, such as addClass()removeClass()toggleClass(), etc. to manipulate the CSS classes assigned to HTML elements.

jQuery addClass() Method

The jQuery addClass() method adds one or more classes to the selected elements.

The following example will add the class .page-header to the <h1> and the class .highlight to the <p> elements with class .hint on button click.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery addClass() Demo</title>
<style>
    .page-header{
        color: red;
        text-transform: uppercase;
    }
    .highlight{
        background: yellow;
    }        
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1").addClass("page-header");
        $("p.hint").addClass("highlight");
    });
});
</script>
</head>
<body>
    <h1>Demo Text</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
    <p class="hint"><strong>Tip:</strong> Lorem Ipsum is dummy text.</p>
    <button type="button">Add Class</button>
</body>
</html>

You can also add multiple classes to the elements at a time. Just specify the space separated list of classes within the addClass() method, like this:

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery addClass() Demo</title>
<style>
    .page-header{
        color: red;
        text-transform: uppercase;
    }
    .highlight{
        background: yellow;
    }         
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1").addClass("page-header highlight");
    });
});
</script>
</head>
<body>
    <h1>Hello World</h1>
    <p>The quick brown fox jumps over the lazy dog.</p>
    <button type="button">Add Class</button>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *