Today I learned about Object.assign() and how it can make DOM node creation code look a bit more compact:
document.body.appendChild(
Object.assign(document.createElement('div'), {
style: 'color: red;',
className: 'foo bar',
textContent: 'Hello, world!'
})
);
Object.assign(target, source) copies all properties from source to target, and returns target.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
@patrickbrosset my personal choice is ~ https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment
@patrickbrosset yes, I use this very frequently, you can define quick helper such as `const el= (tag, idl= null)=> Object.assign(document.createElement(tag), idl);`. There are unfortunately some drawbacks:
- you can use only IDL (https://developer.mozilla.org/en-US/docs/Glossary/IDL)
- `*.append` returns undefined, so it is not easy to create whole template
BTW, I have WIP side-project https://github.com/jaandrle/deka-dom-el (https://jaandrle.github.io/deka-dom-el/p02-elements). There is `assing` function (https://github.com/jaandrle/deka-dom-el/blob/b50f8449aab6ad8445719fa3062e086c6bd83678/src/dom.js#L141) with improvements
@patrickbrosset yes, I use this very frequently, you can define quick helper such as `const el= (tag, idl= null)=> Object.assign(document.createElement(tag), idl);`. There are unfortunately some drawbacks:
- you can use only IDL (https://developer.mozilla.org/en-US/docs/Glossary/IDL)
- `*.append` returns undefined, so it is not easy to create whole template