jQuery Class ManipulationLoading saved progress…

jQuery Class Manipulation

Build jqueryClassManipulation, a small wrapper modeled on jQuery's class methods — .addClass(), .removeClass(), .toggleClass(), and .hasClass(). You're given a single DOM element and return an object whose methods read and write that element's classes. The three mutators return the wrapper itself, so calls chain; hasClass returns a boolean. Each mutator also accepts a space-separated list of class names, just like jQuery.

Signature

interface ClassWrapper {
  addClass(names: string): ClassWrapper;    // add one or more; chainable
  removeClass(names: string): ClassWrapper; // remove one or more; chainable
  toggleClass(names: string): ClassWrapper; // flip one or more; chainable
  hasClass(name: string): boolean;          // is this class present?
}

function jqueryClassManipulation(element: HTMLElement): ClassWrapper;

Examples

const el = document.createElement('div');
const $el = jqueryClassManipulation(el);

$el.addClass('active');     // el.className → 'active', returns the wrapper
$el.hasClass('active');     // → true
$el.removeClass('active');  // el.className → '',       returns the wrapper
// Mutators chain, and toggle flips: 'a b' added, then 'a' toggled off, 'b' stays.
jqueryClassManipulation(el)
  .addClass('a b')
  .toggleClass('a')
  .hasClass('b'); // → true   (a was removed, b is still present)

// A space-separated list addresses several classes in one call:
jqueryClassManipulation(el).addClass('one two three'); // adds all three

Notes

  • Chainable mutators. addClass, removeClass, and toggleClass each return the wrapper so the next method can be called on the result. hasClass is the exception — it returns a boolean.
  • No duplicates. Adding a class the element already has is a no-op; the class list never holds two copies of the same name.
  • Exact matches only. removeClass('btn') on an element with class="btn btn-primary" removes btn and leaves btn-primary intact. Class names are whole tokens, not substrings.
  • Toggle flips state. toggleClass(name) adds the class when it's absent and removes it when it's present.
  • Space-separated lists. Each mutator accepts one name or several names separated by spaces, applying the operation to each.
  • Use the class list. Build on element.classList — its add, remove, toggle, and contains methods handle tokens correctly. Don't hand-edit the className string.
Loading editor…