public
Last active — forked from 1Marc/buildHTML utility

  • Download Gist
buildHTML utility.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// my little html string builder
buildHTML = function(tag, html, attrs) {
// you can skip html param
var h = document.createElement(tag);
var attrs = attrs || {};
if (arguments.length == 2 && !((html) instanceof HTMLElement) && typeof(html) == "object") {
attrs = html;
html = null;
}
for (attr in attrs) {
if(attrs[attr] === false) continue;
h.setAttribute(attr, attrs[attr]);
}
 
if ( html instanceof HTMLElement ){
h.appendChild(html)
} else if ( typeof(html) == "string" ) {
h.appendChild(document.createTextNode(html));
}
return h;
};
 
buildHTML("a", "Marc Grabanski", {
id: "mylink",
href: "http://marcgrabanski.com"
});
// outputs: <a id="mylink" href="http://marcgrabanski.com">Marc Grabanski</a>
 
buildHTML("a", buildHTML("strong", "Marc Grabanski"), {
id: "mylink",
href: "http://marcgrabanski.com"
});
// outputs: <a id="mylink" href="http://marcgrabanski.com"><strong>Marc Grabanski</strong></a>
 
buildHTML("a", {
id: "mylink",
href: "http://marcgrabanski.com"
});
// outputs: <a id="mylink" href="http://marcgrabanski.com"></a>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.