20 January 2024

The addClass function in jQuery and the classList.add method in vanilla JavaScript both serve the purpose of adding one or more CSS classes to HTML elements. jQuery's addClass is succinct and convenient, allowing for easy addition of classes to selected elements, and it can handle multiple classes within a single call. On the other hand, vanilla JavaScript's classList.add is a native DOM method that provides similar functionality but in a more explicit manner. It is part of the modern JavaScript standard and offers a cleaner syntax for manipulating classes on individual elements. While jQuery's addClass is a part of the jQuery library and provides additional cross-browser abstraction, the native classList.add is lightweight and well-suited for modern development, especially when minimizing dependencies is a priority.

Source code viewer
  1. // JQUERY
  2. $("#myElement").addClass("my-class");
  5. // Single element selector.
  6. document.querySelector('#myElement').classList.add("my-class");
  7. // Multi element selector.
  8. document.querySelectorAll('#myElement').forEach(myElement => {
  9. myElement.classList.add("my-class");
  10. });
Programming Language: Javascript