DOM Manipulation

DOM manipulation utility functions in TypeScript are functions that are used to manipulate the Document Object Model (DOM) of a web page. The DOM is a programming interface for web documents that represents the page's content as a tree-like structure of objects.

dom.ts
export const createElement = (
  tagName: string,
  attributes: { [key: string]: string } = {}
): HTMLElement => {
  const element = document.createElement(tagName);
  for (const [attr, value] of Object.entries(attributes)) {
    element.setAttribute(attr, value);
  }
  return element;
};

export const appendChildren = (
  parent: HTMLElement,
  children: (HTMLElement | Text)[]
): void => {
  children.forEach((child) => parent.appendChild(child));
};

export const removeChildren = (parent: HTMLElement): void => {
  while (parent.firstChild) {
    parent.removeChild(parent.firstChild);
  }
};

export const addEventListener = (
  element: HTMLElement,
  event: string,
  handler: (event: Event) => void
): void => {
  element.addEventListener(event, handler);
};

export const removeEventListener = (
  element: HTMLElement,
  event: string,
  handler: (event: Event) => void
): void => {
  element.removeEventListener(event, handler);
};

export const toggleClass = (element: HTMLElement, className: string): void => {
  element.classList.toggle(className);
};

export const addClass = (element: HTMLElement, className: string): void => {
  element.classList.add(className);
};

export const removeClass = (element: HTMLElement, className: string): void => {
  element.classList.remove(className);
};

Last updated