CODING ACADEMY

View Original

How to Add and Remove a Class with jQuery

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:

See this content in the original post

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

See this content in the original post

This produces a simple HTML table as follows:

See this content in the original post

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:

See this content in the original post

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:

See this content in the original post

The complete script is as follows:

See this content in the original post

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.

See this content in the original post

HELP KEEP CODING.ACADEMY AD FREE

See this donate button in the original post