Skip to content

Instantly share code, notes, and snippets.

@timbertson
Created April 3, 2013 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timbertson/5299096 to your computer and use it in GitHub Desktop.
Save timbertson/5299096 to your computer and use it in GitHub Desktop.
var makeDomNode = (function() {
/* convert an arbitrary HTML string -> dom node.
* This function adapted from JQuery code (src/manipulation.js),
* which is distributed under the MIT licence, and is
* Copyright 2013 jQuery Foundation and other contributors
* http://jquery.com/
*/
var rtagName = /<([\w:]+)/;
var wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.col = wrapMap.thead;
wrapMap.th = wrapMap.td;
return function(html) {
var elem = document.createElement('div');
if(html === undefined) return elem;
html = html.replace(/^\s+/, '');
var tag = ( rtagName.exec( html ) || ["", ""] )[ 1 ].toLowerCase();
var wrap = wrapMap[ tag ];
if (wrap) {
elem.innerHTML = wrap[ 1 ] + html + wrap[ 2 ];
var initial_elem = elem;
var j = wrap[ 0 ];
while ( j-- ) {
elem = elem.firstChild;
}
if (elem.childElementCount == 1) {
elem = elem.firstChild;
} else {
// html generated multiple tags, append them to initial_elem and remove wrapper
while (elem.firstChild) {
initial_elem.appendChild(elem.firstChild);
}
elem = initial_elem;
elem.removeChild(elem.firstChild);
}
} else {
// no wrapping required:
elem.innerHTML = html;
// remove the surrogate if there is only one child.
if (elem.childElementCount == 1 && elem.firstChild.nodeType == 1 /* ELEMENT_NODE */) {
elem = elem.firstChild;
}
}
return elem;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment