Re: Convenient way to create element and set its attributes at once
Elliott Sprehn <[email protected]>
| Newsgroups | gmane.comp.web.dom.general |
|---|---|
| Message-ID | <CAPJYB1itM2Wx1ZQvUXnZ7N=S0+HEDvaT7eTAefPqfLGcXptguQ@mail.gmail.com> |
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 <
[email protected]> 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. [email protected]',
> '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.
>
>