mddanishyusuf / dailyhack

🐱‍💻 Tiny Tiny Hacks we use in our daily life.
https://dailyhack.now.sh/
149 stars 15 forks source link

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

Open willhoag opened 5 years ago

willhoag commented 5 years ago

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)
mddanishyusuf commented 5 years ago

@willhoag it's a smart hack.

willhoag commented 5 years ago

Thanks @mddanishyusuf!

Hey, noticing on dailyhack.xyz that the 2nd code block is broken. Just FYI.

https://dailyhack.xyz/post/quick-react-like-api-for-adding-html-to-a-page-in-plain-js-67

mddanishyusuf commented 5 years ago

Thanks @willhoag Now it's fixed. And I also published it.

mddanishyusuf commented 5 years ago

@willhoag how you make the URL you share in the comment. Because the post was not published at that time.?

willhoag commented 5 years ago

@mddanishyusuf Cool, see the fix! Thx!

Oh, it showed up when I clicked on #javascript https://dailyhack.xyz/tag/javascript

Was the first entry...

mddanishyusuf commented 5 years ago

Ohh. You smart man.

I'll fix all these glitches next month. there too much work to finish. Now, I'm busy in my 4th Product of this Year.

willhoag commented 5 years ago

1 product a month then?!! 👀 Nice work, keep it up!!!

mddanishyusuf commented 5 years ago

Thanks, @willhoag