Dynamically Add or Remove CSS Class to a Link Tag using jQuery

← PrevNext →

Here is a simple scenario. You have some link tags on your web page and you want to add or remove the CSS class of the elements based on certain condition. It is very simple if you are using jQuery, as it provides two method called .addClass() and .removeClass(). Here I’ll show you with a simple example on how to dynamically add or remove CSS class of link tags using jQuery methods.

In this example, I am experimenting with the link tags (<a>). You can apply the methods on any HTML element.

I have 3 link tags inside a <div> element. Each tag has a class property called in-active. The in-active class has default values. The idea is, when I click a link, the jQuery methods will change the CSS class of the clicked link, and the class changes to selected. The remaining two links will change back to its original class, that is in-active.

The Markup and the Script
<!DOCTYPE html>
<html>
<head>
    <title>Dynamically Add or Remove CSS Class using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

    <style>
        .selected {
            color:red;
            text-decoration:underlined;
        }
        .in-active {
            color:black;
            text-decoration:none;
        }
    </style>
 </head>
<body>
    <p>Click the links in the box.</p>
    <div>
        <a href="#" class="in-active">Link 1</a><br />
        <a href="#" class="in-active">Link 2</a><br />
        <a href="#" class="in-active">Link 3</a>
    </div>
</body>

<script>
    $(document).ready(function () {
        $('a').click(function () {

            $('a').addClass('in-active');       // ADD CLASS TO ALL THE TAGS.

            if ($(this).hasClass('in-active')) {    // CHECK IF THE TAG HAS 'in-active' CLASS.

                $(this)
                    .removeClass('in-active')
                    .addClass('selected');
            }
        })
    });
</script>
</html>
Try it
Conclusion

Along with the two jQuery methods .addClass() and .removeClass(), I have also included another method in the above example, called .hasClass(). I am checking if the clicked link has the in-active class, then remove the class and add the selected class.

As I said earlier, you can apply this method to any HTML element with ease. You can add more than one class name inside the method separated by a space. For example,

$('a').addClass('class1 class2');

Well, that’s it. Thanks for reading .

← PreviousNext →