lib-dommy
v1.0.2
Published
A simple wrapper for the DOM API
Downloads
3
Readme
Dommy
Generate dynamic nested HTML fragments with JavaScript
What is Dommy?
Sometimes it's necessary to make multiple HTML elements as part of a single entity. For example, a panel might have an outer element for the styling and an inner element to hold the content. Dommy allows you to create the entire entity with one function call.
Why is this useful?
This is a tool I created for myself after finding that I often had to create complex hierarchies to programmatically create HTML elements. For example, here's how to make such an element with calls to document.createElement()
:
function makePanel() {
var fragment = document.createDocumentFragment();
var panel = document.createElement('div');
var content = document.createElement('div');
panel.classList.add('panel');
content.classList.add('panel-body');
content.innerText = 'Isn't this exhausting?';
panel.appendChild(content);
fragment.appendChild(panel);
return fragment;
}
With Dommy you can do the same thing with one function call:
var panel = dommy.create({ element: 'div.panel', nested: { element: 'div.panel-body', content: 'Isn't this less exhausting?'}});
How do I use it?
Like so:
var dommy = require('lib-dommy');
var dommyElement = dommy.create({
element: 'div.your.classes.here',
content: 'Some text to enter here.',
id: 'your-id',
data: {
loaded: 'this will show up as data-loaded',
opened: 'and this will be data-opened'
},
nested: [{
id: 'first-sub-item',
element: 'div.sub-item',
content: 'And this will be embedded inside of the parent element.'
}, {
id: 'second-sub-item',
element: 'div.sub-item',
content: 'And this will be a sibling to the first sub-item.'
}]
});
dommy.create()
returns a DocumentFragment containing all of the nested HTML. Therefore, you can use all of the regular methods for adding the resulting element to the DOM:
// jQuery append:
$('body').append(dommyElement);
// document API:
document.body.appendChild(dommyElement);