Last active
April 1, 2017 02:56
-
-
Save paolocaminiti/df203b27f63debb76378 to your computer and use it in GitHub Desktop.
DOM fragment or HTML string to JSONML serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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