#create
declarative element creation for the browser. no dependencies.
##installation
npm install create.js
##usage
var create = require('create.js');
create[tagName](options)
###example
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: '<div class="thing"></div>'
});
<div class="class class2" id="identifier"><div class="thing"></div></div>
calls to create can be nested
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: create.p({content:'hi there'})
});
<div class="class class2" id="identifier"><p>hi there</p></div>
###create.list
var things = [ 'thing1', 'thing2' ];
var ul = create.ul({
classes: ['class', 'class2'],
id: 'identifier',
content: create.list(things, function() {
return create.li({content:this.current});
}),
});
<ul class="class class2" id="identifier">
<li>thing1</li>
<li>thing2</li>
</ul>
create.list takes an iterable and a callback as parameters. the function is called for each item in the iterable, passing the current item as the only parameter. it expects an element to be returned from the function. behind the scenes, a document fragment is created and returned with the result of each function call appended as a child.
content can also be set as a function.
var things = [ 'thing1', 'thing2' ];
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: function() {
var fragment = create.fragment();
var header = create.h1({content:'Things'});
fragment.appendChild(header);
things.forEach(function(thing) {
var p = create.p({content:thing});
fragment.appendChild(p);
});
return fragment;
}
});
<div class="class class2" id="identifier">
<h1>Things</h1>
<p>thing1</p>
<p>thing2</p>
</div>
or an array.
<div id="thing"></div>
var thing = document.querySelector('#thing');
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: [create.p({content:'thing1'}), thing, create.p({content:'thing2'})]
});
<div class="class class2" id="identifier">
<p>thing1</p>
<div id="thing"></div>
<p>thing2</p>
</div>
create.fragment with no params creates and returns an empty document fragment.
pass attributes to options to set on returned element.
classes property can be a string or list.
more fleshed out example
var container = create.div({
classes: 'container',
id: 'container',
context: { things: ['thing1', 'thing2']},
content: function(context) {
return create.div({
id: 'inner',
context: context.things,
content: function(context) {
var fragment = create.fragment();
context.forEach(function(thing) {
var child = create.a({
href: 'http://github.com/ergusto',
content: thing
});
fragment.appendChild(child);
});
return fragment;
}
});
},
});
<div class="container" id="container">
<div id="inner">
<a href="http://github.com/ergusto">thing1</a>
<a href="http://github.com/ergusto">thing2</a>
</div>
</div>