Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@0xdevalias
Forked from 1Marc/buildHTML utility
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 0xdevalias/11339206 to your computer and use it in GitHub Desktop.
Save 0xdevalias/11339206 to your computer and use it in GitHub Desktop.
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