Skip to content

Instantly share code, notes, and snippets.

@0xdevalias
Forked from 1Marc/buildHTML utility
Last active October 15, 2024 07:35
Show Gist options
  • 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