Advertisement
didkoslawow

Untitled

May 28th, 2023 (edited)
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     function createElement(tagName, textContent, attributes, children = []) {
  2.  
  3. // Създаваме елемент от подадения тип.
  4.         const element = document.createElement(tagName);
  5.  
  6. // Създаваме речник (обект) с възможните атрибути. Използваме arrow функции, за да предадем стойността на атрибута, ако има такава. При нужда, може да се добавят нови ентрита в речника.
  7.         const PARAMS = {
  8.             class: (value) => element.classList.add(value),
  9.             id: (value) => (element.id = value),
  10.             onclick: (value) => element.addEventListener('click', value),
  11.             disabled: () => element.setAttribute('disabled', ''),
  12.             src: (value) => element.setAttribute('src', value),
  13.         };
  14.  
  15. // Проверяваме дали има подаден textContent, ако има го сетваме на елемента.
  16.         if (textContent) {
  17.             element.textContent = textContent;
  18.         }
  19.  
  20. // Проверяваме дали има подадени атрибути (подават се като обект). Ако има, преобразуваме обекта в масив от масиви, обхождаме го и повикваме съответната функция от речника, за да сетне атрибута.
  21.         if (attributes) {
  22.             Object.entries(attributes).forEach(([param, value]) => PARAMS[param](value));
  23.         }
  24.  
  25. // Проверяваме дали има подадени деца (подават се като масив), (Нестнато създаване на елементи, виж примера долу). Ако няма, връщаме елемента.
  26.         if (children.length == 0) {
  27.             return element;
  28.         }
  29.  
  30. // Ако има подадени деца, обхождаме масива и всяко дете, добавяме към елемента.
  31.         children.forEach((c) => element.appendChild(c));
  32.  
  33.         return element;
  34.     }
  35.  
  36. // Пример за използване:
  37. const divContainer = createElement('div', null, { class: 'container', onclick: onRepair },
  38.         [
  39.             createElement('h2', `Product type for repair: ${productType}`),
  40.             createElement('h3', `Client information: ${clientName}, ${clientPhone}`),
  41.             createElement('h4', `Description of the problem: ${description}`),
  42.             createElement('button', 'Start repair', { class: 'start-btn' }),
  43.             createElement('button', 'Finish repair', { class: 'finish-btn', disabled: true }),
  44.         ]
  45. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement