Skip to content

Instantly share code, notes, and snippets.

@eligrey
Created July 2, 2011 01:12
Show Gist options
  • Save eligrey/1059648 to your computer and use it in GitHub Desktop.
Save eligrey/1059648 to your computer and use it in GitHub Desktop.
Some tools for making HTML documents from HTML fragments
(function() {
"use strict";
var
guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, charset = "UTF-8"
;
if (html.ownerDocument) {
charset = html.ownerDocument.characterSet;
}
charset_meta.setAttribute("charset", charset);
if (typeof html === "string") {
body.innerHTML = html;
} else {
body.appendChild(doc.importNode(html, true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
exports.guess_title = guess_title;
exports.create_html_doc = create_html_doc;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment