willhoag
3 months ago

Quick React-like API for adding html to a page in plain JS

I use this when need to quickly add some HTML to a page programmatically.

Code is:

function el (type, attrs, children) {
  children = children || []
  attrs = attrs || {}
  var e = document.createElement(type)
  Object.keys(attrs).forEach(function (key) {
    e.setAttribute(key, attrs[key])
  })
  children.forEach(function (child) {
    if (typeof child === 'string') {
      if (e.textContent) {
        e.textContent = child
      } else {
        e.innerHTML = child
      }
    } else {
      e.appendChild(child)
    }
  })
  return e
}

And usage:

const newElement = (
  el('div', { className: 'bold' }, [
    el('p', {}, ['here is text in a paragraph'])
  ])
)

document.appendChild(newElement)
Do you have any comment on this tricks? then let the author know about that. comment here