Advertisement
GalinaKG

Create DOM Elements Function

Apr 3rd, 2023
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function createElement(type, parentNode, content, classes, id, attributes, useInnerHtml) {
  2.     const htmlElement = document.createElement(type);
  3.  
  4.     if (content && useInnerHtml) {
  5.       htmlElement.innerHTML = content;
  6.     } else {
  7.       if (content && type !== 'input') {
  8.         htmlElement.textContent = content;
  9.       }
  10.  
  11.       if (content && type === 'input') {
  12.         htmlElement.value = content;
  13.       }
  14.     }
  15.  
  16.     if (classes && classes.length > 0) {
  17.       htmlElement.classList.add(...classes);
  18.     }
  19.  
  20.     if (id) {
  21.       htmlElement.id = id;
  22.     }
  23.  
  24.     // { src: 'link', href: 'http' }
  25.     if (attributes) {
  26.       for (const key in attributes) {
  27.         htmlElement.setAttribute(key, attributes[key])
  28.       }
  29.     }
  30.  
  31.     if (parentNode) {
  32.       parentNode.appendChild(htmlElement);
  33.     }
  34.  
  35.     return htmlElement;
  36.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement