Skip to content

Instantly share code, notes, and snippets.

@ThisIsMissEm
Forked from 1Marc/buildHTML utility
Created July 13, 2010 09:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThisIsMissEm/473655 to your computer and use it in GitHub Desktop.
Save ThisIsMissEm/473655 to your computer and use it in GitHub Desktop.
// 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment