All files / src/core/dom classes.ts

100% Statements 19/19
100% Branches 10/10
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59    4x             7x             4x   11x   11x 9x 9x 11x                   4x   7x   7x 5x 5x 6x                     4x 4x 2x   2x      
import { isString } from 'core/utils/types';
 
const rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
 
/**
 * Check whether the given element has the given class name.
 * @param elm The element.
 * @param className The class name.
 */
export const hasClass: (elm: Element, className: string) => boolean = (elm, className) => elm.classList.contains(className);
 
/**
 * Adds the given class name(s) to the given element.
 * @param elm The element.
 * @param className The class name(s) which shall be added. (separated by spaces)
 */
export const addClass: (elm: Element, className: string) => void = (elm, className) => {
  let clazz: string;
  let i = 0;
 
  if (isString(className)) {
    const classes: Array<string> = className.match(rnothtmlwhite) || [];
    while ((clazz = classes[i++])) {
      elm.classList.add(clazz);
    }
  }
};
 
/**
 * Removes the given class name(s) from the given element.
 * @param elm The element.
 * @param className The class name(s) which shall be removed. (separated by spaces)
 */
export const removeClass: (elm: Element, className: string) => void = (elm, className) => {
  let clazz: string;
  let i = 0;
 
  if (isString(className)) {
    const classes: Array<string> = className.match(rnothtmlwhite) || [];
    while ((clazz = classes[i++])) {
      elm.classList.remove(clazz);
    }
  }
};
 
/**
 * Adds or removes the given class name(s) from the given element depending on the given condition.
 * Condition true means add class name(s), false means remove class name(s).
 * @param elm The element.
 * @param className The class name(s) which shall be added or removed. (separated by spaces)
 */
export const conditionalClass: (elm: Element, className: string, condition: boolean) => void = (elm, className, condition) => {
  if (condition) {
    addClass(elm, className);
  } else {
    removeClass(elm, className);
  }
};