Skip to content

Instantly share code, notes, and snippets.

@chrismllr
Last active July 10, 2017 22:41
Show Gist options
  • Save chrismllr/4d1a9f2d4fed245bb3b9fe157e2fc487 to your computer and use it in GitHub Desktop.
Save chrismllr/4d1a9f2d4fed245bb3b9fe157e2fc487 to your computer and use it in GitHub Desktop.
Helpers for generating DOM nodes.
import set from 'lodash.set';
/*
New DOM node.
arguments:
nodeType (string) 'div': name of the DOM element
children (ArrayOf[n, t, svg]): Child nodes
opts (Object): element attributes. className, id, etc
Usage:
n(
'div',
[
t('Heres some base text),
n('p', [t('This is a p tag within the div')]),
svg('<svg><path /></svg>)
],
{
className: 'example example--modifier'
}
)
*/
export function n(nodeType, children, opts = {}) {
const node = document.createElement(nodeType);
children.forEach((child) => {
node.appendChild(child);
});
function assign (k) {
set(node, k, opts[k]);
}
Object.keys(opts).forEach(assign);
return node;
}
/*
New TEXT node.
arguments:
text (string): Text to be rendered to a textNode.
Usage:
t('This is a p tag within a div!')
*/
export function t(text) {
return document.createTextNode(text);
}
/*
New SVG node. Will build an actual DOM representation of an SVG.
arguments:
str (string): SVG in string format
Usage:
svg('<svg></svg>');
*/
export function svg(str) {
const parser = new DOMParser();
const rendered = parser.parseFromString(str, 'image/svg+xml');
return rendered.documentElement;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment