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

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