How to Add and Remove a Class with jQuery

 
 
jquery logo.png
 

In this lesson we look at an extremely simple yet powerful function within jQuery - the ability to add and remove a class.

As an example, click on a checkbox in the table below and see how the whole row is highlighted:

Check ID Name
1 Bob
2 Sally

The following page structure shows the results from an example database call. The records are presented in a table.

This produces a simple HTML table as follows:

Check ID Name
1 Bob
2 Sally

As you can see there is an option to check a box next to each row.

Notice how the row does not yet highlight as we have not yet added the jQuery code to add and remove the class.

We can use jQuery to highlight the whole row when a checkbox has been ticked. Since Bootstrap has been included we can use the .bg-success class to highlight the checked row in green.

The code is as follows:

Line 1: we check if a checkbox has been clicked

Line 2: set a variable called row to be the closest tr

Line 3: check if the checkbox is ticked

Line 4: add the class .bg-success to the row

Line 5: else check of the checkbox is not ticked

Line 6: remove the class .bg-success from the row

The result looks like this:

Check ID Name
1 Bob
2 Sally

The complete script is as follows:

NEXT STEPS?

I actually use this quite a lot when I have a table with a delete icon. Clicking on the delete icon will highlight the row in red, then slowly animate the removal of the row. Give it a try below.

ID Name Delete
1 Bob
2 Sally

HELP KEEP CODING.ACADEMY AD FREE

Donate $1