Skip to content

Instantly share code, notes, and snippets.

@paolocaminiti
Last active November 30, 2015 19:09
Show Gist options
  • Select an option

  • Save paolocaminiti/5a169ea7b42dcf947912 to your computer and use it in GitHub Desktop.

Select an option

Save paolocaminiti/5a169ea7b42dcf947912 to your computer and use it in GitHub Desktop.
DOM fragment or HTML string to an immediate object rappresentation, parsable just as real DOM
/**
* DOM fragment or HTML string to an immediate object rappresentation, parsable just as real DOM.
* ex. {
* attributes: [
* { name: 'id', value: 'unique' },
* { name: 'class', value: 'class class2' },
* { name: 'style', value: 'color: hotpink' },
* ...
* ],
* childNodes: [
* {
* data: "text node, could have been a nested element",
* nodeName: '#text',
* nodeType: 3
* },
* ...
* ],
* nodeName: 'div',
* nodeType: 1
* }
*
* @param {(string|DOM Fragment)} frag The piece of static DOM to convert.
* @return {object} The object with and exact subset interface of a real piece of DOM.
*/
var dom2domobj = (function () {
function asDOMObject(frag) {
var el = {
attributes: [],
childNodes: [],
nodeName: frag.nodeName,
nodeType: frag.nodeType
}
var attrs = frag.attributes
if (attrs) {
for (var a = 0; a < attrs.length; a++) {
var attr = attrs[a]
el.attributes.push({ name: attr.name, value: attr.value })
}
}
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.childNodes.push(asDOMObject(node))
} else if (nodeType === 3) {
el.childNodes.push({ data: node.data, nodeName: '#text', nodeType: 3 })
}
}
return el
}
function parse(frag) {
if (typeof frag === 'string') {
var f = document.createElement('span')
f.innerHTML = frag
frag = f
}
return asDOMObject(frag)
}
return parse
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment