Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created July 17, 2015 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barneycarroll/f43637d3d686a36c71c1 to your computer and use it in GitHub Desktop.
Save barneycarroll/f43637d3d686a36c71c1 to your computer and use it in GitHub Desktop.
Convert DOM or XML/HTML to Mithril
const { map, reduce } = Array.prototype
const wrap = document.createElement( 'x' )
export const dom2mithril = dom =>
dom.nodeType === 3
? dom.nodeValue
: dom.nodeType === 1
? {
tag : dom.nodeName,
attrs : dom.attributes
::reduce( ( attrs, attr ) =>
( {
...attrs,
[ attr.name ] : attr.value
} ),
{}
),
children : dom.childNodes
::map( dom2mithril )
}
: null
export const html2mithril = html => {
while ( wrap.hasChildNodes() )
wrap.removeChild( wrap.lastChild )
return wrap
.insertAdjacentHTML( 'beforeend', markup )
.childNodes
::map( dom2mithril )
}
( this.define || Object )(
( this.exports || this ).module = {
dom2mithril : function( dom ){
return dom.nodeType === 3
? dom.nodeValue
: dom.nodeType === 1
? {
tag : dom.nodeName,
attrs : Array.prototype.reduce.call(
dom.attributes,
function( attrs, attr ){
attrs[ attr.name ] = attr.value
return attrs
},
{}
),
children : Array.prototype.map.call( dom.childNodes, this.dom2mithril )
}
: null
},
html2mithril : function( html ){
while ( wrap.hasChildNodes() )
wrap.removeChild( wrap.lastChild )
wrap.insertAdjacentHTML( 'beforeend', markup )
return Array.prototype.map.call( childNodes, this.dom2mithril )
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment