All files Dom.ts

100% Statements 17/17
100% Branches 8/8
100% Functions 3/3
100% Lines 15/15

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                  2x         14x   14x 12x 12x       14x 13x 13x 14x       14x               2x 7x                 14x 11x   3x      
type Attributes = { [key: string]: string };
type Child = Element | string;
 
/**
 * Creates HTML element
 * @param tag - element's tag name
 * @param attributes - element's attributes
 * @param children - element's children
 */
export function CreateElement(
  tag: string,
  attributes?: Attributes,
  children?: Child[] | Child
): Element {
  const el: Element = document.createElement(tag); // create dom element
 
  if (attributes) {
    for (let [key, value] of Object.entries(attributes)) {
      el.setAttribute(key, value); // set attributes to element
    }
  }
 
  if (children) {
    if (!Array.isArray(children)) children = [children];
    for (const child of children) {
      AppendChild(el, child); // add children to element
    }
  }
 
  return el;
}
 
/**
 * Removes all children from an element
 * @param parent
 * @constructor
 */
export function RemoveChildren(parent: Element): void {
  while (parent.firstChild) parent.removeChild(parent.lastChild!); // remove children from parent element
}
 
/**
 * Appends child element to parent
 * @param parent - parent element
 * @param child - child element
 */
function AppendChild(parent: Element, child: Child): void {
  if (typeof child === "string") {
    parent.appendChild(document.createTextNode(child)); // add text for parent element
  } else {
    parent.appendChild(child); // add children for parent element
  }
}