npm install create.js#create
declarative element creation for the browser. no dependencies.
##installation
npm install create.js
##usage
``javascript`
var create = require('create.js');
createtagName
###example
`javascript`
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: ''
});
`html`
calls to create can be nested
`javascript`
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: create.p({content:'hi there'})
});
` hi therehtml`
###create.list
`javascript`
var things = [ 'thing1', 'thing2' ];
`javascript`
var ul = create.ul({
classes: ['class', 'class2'],
id: 'identifier',
content: create.list(things, function() {
return create.li({content:this.current});
}),
});
`html`
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.
`javascript`
var things = [ 'thing1', 'thing2' ];
`javascript`
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;
}
});
` thing1 thing2html`
Things
---
or an array.
`html`
`javascript`
var thing = document.querySelector('#thing');
var element = create.div({
classes: ['class', 'class2'],
id: 'identifier',
content: [create.p({content:'thing1'}), thing, create.p({content:'thing2'})]
});
` thing1 thing2html`
---
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
`javascript`
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;
}
});
},
});
`html``