create.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { isString } from '../../type/type';
  2. import { addClass } from '../addClass/addClass';
  3. import { append } from '../append/append';
  4. import { setAttribute } from '../setAttribute/setAttribute';
  5. export function create<K extends keyof HTMLElementTagNameMap>(
  6. tag: K,
  7. attrs?: Record<string, string | number | boolean> | string,
  8. parent?: HTMLElement
  9. ): HTMLElementTagNameMap[ K ];
  10. export function create(
  11. tag: string,
  12. attrs?: Record<string, string | number | boolean> | string,
  13. parent?: HTMLElement
  14. ): HTMLElement;
  15. /**
  16. * Creates a HTML element.
  17. *
  18. * @param tag - A tag name.
  19. * @param attrs - Optional. An object with attributes to apply the created element to, or a string with classes.
  20. * @param parent - Optional. A parent element where the created element is appended.
  21. */
  22. export function create<K extends keyof HTMLElementTagNameMap>(
  23. tag: K,
  24. attrs?: Record<string, string | number | boolean> | string,
  25. parent?: HTMLElement
  26. ): HTMLElementTagNameMap[ K ] {
  27. const elm = document.createElement( tag );
  28. if ( attrs ) {
  29. isString( attrs ) ? addClass( elm, attrs ) : setAttribute( elm, attrs );
  30. }
  31. parent && append( parent, elm );
  32. return elm;
  33. }