Convenient way to create element and set its attributes at once

Hello.

Creating an element via DOM is often followed by setting its attributes one by one:

ššššvar input = document.createElement('input');
ššššinput.setAttribute('type', 'email');
ššššinput.setAttribute('name', 'foo');
ššššinput.setAttribute('size', 100);
ššššinput.setAttribute('placeholder', 'Some placeholder text');
ššššinput.setAttribute('required', '');

It may make sense to make such general sequence of operations more convenient/nonredundant by extending the existing `document.createElement()` method with optional second parameter that could be used to pass element's attributes' map (key-value pairs as an Object):

ššššvar input = document.createElement('input', {
šššššššš'type' : 'email',
šššššššš'name' : 'foo',
šššššššš'size' : 50,
šššššššš'placeholder' : 'e.g. example@example.com',
šššššššš'required' ššš: ''
šššš});

ššššvar a = document.createElement('a', {
šššššššš'href' š: '/example/',
šššššššš'title' : 'Example link'
šššš});

ššššvar label = document.createElement('label', {
šššššššš'for' : 'some-field'
šššš});

Also, `element.setAttribute()` method could be extended to make it possible to set multiple attributes at once by accepting key-value map of attributes and their values as the first and only argument:

ššššelement.setAttribute({
šššššššš'id' šššš: 'foo',
šššššššš'class' š: 'lorem ipsum dolor',
šššššššš'data-i' : 42
šššš});

Thanks.

Received on Thursday, 21 November 2013 23:48:52 UTC