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

Marat Tanalin <[email protected]>
Newsgroups gmane.comp.web.dom.general
Message-ID <[email protected]>
02.12.2013, 08:06, "Elliott Sprehn" <[email protected]>:
> On Thu, Nov 21, 2013 at 6:48 PM, Marat Tanalin | tanalin.com <[email protected]> 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. [email protected]',
>>         '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. [email protected]',
         '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+).
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.