W3C home > Mailing lists > Public > www-dom@w3.org > October to December 2013

Convenient way to create element and set its attributes at once

From: Marat Tanalin | tanalin.com <mtanalin@yandex.ru>
Date: Fri, 22 Nov 2013 03:48:08 +0400
To: "www-dom@w3.org" <www-dom@w3.org>
Message-Id: <136321385077688@web17h.yandex.ru>
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

This archive was generated by hypermail 2.3.1 : Tuesday, 20 October 2015 10:46:21 UTC