Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple little method to build a html element form the given data object.
/* buildHtml - Helper method to construct html tags easily */
var buildHtml = function(tag, attrs, innerHtml) {
var h = '<' + tag;
for (var attr in attrs) {
if(attrs[attr] === false) {
continue;
}
h += ' ' + attr + '="' + attrs[attr] + '"';
}
return h += innerHtml ? '>' + innerHtml + '</' + tag + '>' : '/>';
}
buildHTML("a", {
id: "mylink",
href: "http://devalias.net/"
}, "Glenn devalias Grant");
// outputs: <a id="mylink" href="http://devalias.net">Glenn devalias Grant</a>
// or leave out the innerHtml
buildHTML("input", {
id: "myinput",
type: "text",
value: "myvalue"
});
// outputs: <input id="myinput" type="text" value="myvalue" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment