3 ms·
An even simpler bit of sugar over the DOM that I embed whenever I need just a little bit of JS: function $E(t,p,c) { const el=document.createElement(t)
by wolfgang42 4y ago
An even simpler bit of sugar over the DOM that I embed whenever I need just a little bit of JS:
function $E(t,p,c) {
const el=document.createElement(t)
Object.assign(el,p)
el.append(...c)
return el
}
Usage:
const button = $E('button', {onclick: () => alert('click!')}, [
$E('img', {src: '/assets/icon-lightbulb.png'}, []),
'Ding!',
])
(With thanks to 'goranmoomin: https://news.ycombinator.com/item?id=23590750 https://news.ycombinator.com/item?id=23590750)
- goranmoomin 4y agoOh, didn’t expect a reference to me at all, was thinking that the function was very similar to mine :) That function is now in my must-haves in my new Django side projects; I usually overuse them before I finally move to a JSX-based UI library. It’s great for simple DOM manipulation… and for me it seems to create a semi-simple migration path in the case the code gets complex.
- SCLeo 4y agoWow! What a coincidence! I literally have something extremely similar which I called `$e`. I think one crucial thing you did not mention is that this conforms to the signature of jsxFactory, meaning if you run some kind of transpiler that supports jsx, you can literally do: parent.append(<p>Hello</p>); (Mine has slightly more functionalities, such as allowing passing in styles as a object, auto concatenate array of strings for class names, etc.)
- cnity 4y agoJoining this thread to say that I, too, have written a very similar function and also use jsxFactory to have JSX support in personal projects. I find that using it along with an extremely simple implementation of a kind of state listener[0] produces something really nice for small projects. It's a bit like a jquery for the '20s. [0] https://github.com/curlywurlycraig/vdom-util/blob/master/src/utils/atom.js https://github.com/curlywurlycraig/vdom-util/blob/master/src...