Skip to content

Instantly share code, notes, and snippets.

@paolocaminiti
Last active April 1, 2017 02:56
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 paolocaminiti/df203b27f63debb76378 to your computer and use it in GitHub Desktop.
Save paolocaminiti/df203b27f63debb76378 to your computer and use it in GitHub Desktop.
DOM fragment or HTML string to JSONML serializer
/**
* DOM fragment or HTML string to JSONML serializer.
* @param {(string|DOM Fragment)} frag The piece of static DOM to convert.
* @return {array} The JSONML serialization of frag.
*/
var dom2jsonml = (function () {
function asJSONML(frag) {
var el = [frag.nodeName]
var elAttributes = {}
var attrs = frag.attributes
if (attrs) {
for (var a = 0; a < attrs.length; a++) {
var attr = attrs[a]
elAttributes[attr.name] = attr.value
}
el.push(elAttributes)
}
var childNodes = frag.childNodes
for (var i = 0, len = childNodes.length; i < len; i++) {
var node = childNodes[i]
var nodeType = node.nodeType
if (nodeType === 1) {
el.push(asJSONML(node))
} else if (nodeType === 3) {
el.push(node.data)
}
}
return el
}
function parse(frag) {
if (typeof frag === 'string') {
var f = document.createElement('span')
f.innerHTML = frag
frag = f
}
return asJSONML(frag)
}
return parse
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment