Create Element with attributes in one line

We normally use this kind of code to create a HTML element with JS:

const a = document.createElement('a')
a.setAttribute('class', 'foo bar')
a.setAttribute('id', 'id')
a.setAttribute('innerHTML', 'Hello World!')
a.setAttribute('href', 'https://www.google.com/')


Or some similar ways. But setting each attribute one by one is tedious!

We can do this in a single line if we want:

Object.assign(document.createElement('a'), {
  id: 'id',
  class: 'whatever class',
  href: 'https://www.google.com/',
  innerHTML: 'This is a link'
});


One more way to mess up with your JS codebase!

21
Babar

Get our stories delivered

From us to your inbox weekly.