JSFiddle - React, Tailwind, and code Playground
by jsumners
JavaScript
/**
* Returns a document fragment that represents a new HTML
* element. The element will be of the type specified in
* `element` with the content specified by `content`. The
* attributes on the element are provided by the `attributes`
* parameter. This should be an object with keys representing
* the attribute names. The values of the object properties
* will be the values of the attributes.
*/
function tmpl(element, attributes, content) {
var returnObj = document.createDocumentFragment(),
ele, prop;
if (typeof element !== "string") {
throw new Error("The element parameter must be a String.");
}
if (Object.prototype.toString.call(attributes) !== "[object Object]") {
throw new Error("The element parameter must be an Object.");
}
ele = document.createElement(element);
if (typeof content === "string") {
ele.textContent = content;
} else {
// Assume it is something we can append.
ele.appendChild(content);
}
for (prop in attributes) {
if (!attributes.hasOwnProperty(prop)) {
continue;
}
ele.setAttribute(prop, attributes[prop]);
}
returnObj.appendChild(ele);
return returnObj;
}
var attrs = {"data-foo":"bar", "data-bar": 42};
$('body').append( tmpl('div', attrs, 'This is a test!') );