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

Re: Convenient way to create element and set its attributes at once

From: Elliott Sprehn <esprehn@gmail.com>
Date: Sun, 1 Dec 2013 23:05:55 -0500
Message-ID: <CAPJYB1itM2Wx1ZQvUXnZ7N=S0+HEDvaT7eTAefPqfLGcXptguQ@mail.gmail.com>
To: "Marat Tanalin | tanalin.com" <mtanalin@yandex.ru>
Cc: "www-dom@w3.org" <www-dom@w3.org>
I believe we should just solve this with the constructor syntax:

new HTMLDivElement({
  id: "foo"
});

and

new HTMLHeadingElement("h1", {
  id: "foo"
});



On Thu, Nov 21, 2013 at 6:48 PM, Marat Tanalin | tanalin.com <
mtanalin@yandex.ru> wrote:

> 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 Monday, 2 December 2013 04:07:03 UTC

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