All files / src/dom createElement.ts

100% Statements 13/13
100% Branches 14/14
100% Functions 2/2
100% Lines 13/13

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                    646x   646x 541x     646x 329x     646x 1282x 426x     856x 110x 110x     746x     646x    
export interface CreateElementOptions {
  className?: string;
  text?: string;
  attributes?: Record<string, string | boolean | number | null | undefined>;
}
 
export function createElement<K extends keyof HTMLElementTagNameMap>(
  tagName: K,
  options: CreateElementOptions = {}
): HTMLElementTagNameMap[K] {
  const element = document.createElement(tagName);
 
  if (options.className) {
    element.className = options.className;
  }
 
  if (options.text !== undefined) {
    element.textContent = options.text;
  }
 
  Object.entries(options.attributes ?? {}).forEach(([name, value]) => {
    if (value === undefined || value === null || value === false) {
      return;
    }
 
    if (value === true) {
      element.setAttribute(name, "");
      return;
    }
 
    element.setAttribute(name, String(value));
  });
 
  return element;
}