Convenient way to create element and set its attributes at once
Marat Tanalin | tanalin.com <[email protected]>
| Newsgroups | gmane.comp.web.dom.general |
|---|---|
| Message-ID | <[email protected]> |
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.