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

02.12.2013, 08:06, "Elliott Sprehn" <esprehn@gmail.com>:
> 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:
>>
>> 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'    : ''
>>     });
>>
> I believe we should just solve this with the constructor syntax:
> new HTMLDivElement({
> š id: "foo"
> });
>
> and
>
> new HTMLHeadingElement("h1", {
> š id: "foo"
> });

Whether to use constructors or factory methods is another story.

Aside from that, having ability to create an object directly (as an alternative to a factory method) does make sense, but names like `HTMLDivElement` or `HTMLHeadingElement` are probably too verbose/redundant and not too intuitive/easy-to-remember and maybe even error-prone, and therefore there is a risk that web developers will just not use them (e.g. I wouldn't).

It would probably be more usable to have simple `Element` constructor with same arguments as `document.createElement()` method (including optional second argument containing attributes' map as I've proposed):

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

It would also be consistent with already existing web-developer-friendly constructors like `new Text` and `new Comment` (implemented in Firefox 24+, Chrome 28+, and Opera 15+).

Received on Monday, 2 December 2013 23:59:54 UTC