Handling Classes with jQuery
This YouTube video was created by Steve Griffith.
Just like in JavaScript, one of the most common tasks to complete with jQuery is adding and removing classes from elements. There are 4 jQuery methods for manipulating the [Class Attribute], which are: addClass()
, removeClass()
, toggleClass()
, and hasClass()
.
Again, let assume we have the following HTML:
<main>
<p class="first">Lorem ipsum dolor sit</p>
<p class="second">Lorem ipsum dolor sit</p>
<p class="third">Lorem ipsum dolor sit</p>
</main>
We can remove a class to first paragraph like so:
// jQuery
$('.first').removeClass('first')
// Vanilla JavaScript
document.querySelector('.first').classList.remove('first')
We can add a class to multiple elements in a similar way:
// jQuery
$('p').addClass('active')
// Vanilla JavaScript
document.querySelectorAll('p').forEach(p => p.classList.add('active'))