Email or username:

Password:

Forgot your password?
Patrick Brosset

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.
developer.mozilla.org/en-US/do

2 comments
Jan Andrle

@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 (developer.mozilla.org/en-US/do)
- `*.append` returns undefined, so it is not easy to create whole template

BTW, I have WIP side-project github.com/jaandrle/deka-dom-e (jaandrle.github.io/deka-dom-el). There is `assing` function (github.com/jaandrle/deka-dom-e) 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 (developer.mozilla.org/en-US/do)
- `*.append` returns undefined, so it is not easy to create whole template

Go Up