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

On Fri, 22 Nov 2013, Marat Tanalin | tanalin.com wrote:
> 
> Creating an element via DOM [...]

In my own projects, I've ended up rolling my own function to do this:

   E(tagName);
   E(tagName, propertiesAndAttributes);
   E(tagName, contents...);
   E(tagName, propertiesAndAttributes, contents...);

This functions creates an element where:

   tagName is a string like 'h1' or 'form', giving the element's type.
   (We could support SVG and MathML with tag names of the form "svg:g".)

   propertiesAndAttributes is an object whose properties are each 
   processed as follows:
      -- if the value is the boolean false value, it's ignored
      -- if the value is the boolean true value, a content attribute with 
         the same name as the key is set to the empty string
      -- if the value is a string, a content attribute with the same name
         as the key is set to the given value
      -- if the value is a function, the property with the same name is
         set to the given value

   contents is zero or more of the following, procesed as follows:
      -- arrays are processed recursively.
      -- nulls are ignored
      -- strings are treated as text nodes to append to the element
      -- nodes are appended to the element

Thus you can do things like:

   E('p', E('label', 'Username: ', E('input', { name: 'username', required: true })));

...as the equivalent of:

   <p><label>Username: <input name=username required></label></p>

...or this:

   var button = E('button', { onclick: handleClick, disabled: isDisabled },
                            'Continue');

...as the equivalent of:

   var button = document.createElement('button');
   button.onclick = handleClick;
   if (isDisabled)
     button.disabled = true;
   button.textContent = document.createTextNode('Continue');

(I also have an F() function that returns a DocumentFragment, which just 
takes the equivalent of "contents" above as its arguments.)

Having said that, personally I prefer E4H as a solution to all this.

   http://hixie.ch/specs/e4h/strawman

-- 
Ian Hickson               U+1047E                )\._.,--....,'``.    fL
http://ln.hixie.ch/       U+263A                /,   _.. \   _\  ;`._ ,.
Things that are impossible just take longer.   `._.-(,_..'--(,_..'`-.;.'

Received on Tuesday, 3 December 2013 03:58:43 UTC