Skip to content

Instantly share code, notes, and snippets.

@AndersDJohnson
Last active June 5, 2019 13:34
Show Gist options
  • Select an option

  • Save AndersDJohnson/4450366 to your computer and use it in GitHub Desktop.

Select an option

Save AndersDJohnson/4450366 to your computer and use it in GitHub Desktop.
node-htmlparser toHTML module
htmlparser = require 'htmlparser'
emptyTags = htmlparser.DefaultHandler._emptyTags
render = (dom) ->
stack = []
for node in dom
switch node.type
when 'text'
stack.push node.data
when 'comment'
stack.push '<!--' + node.data + '-->'
when 'tag'
stack.push '<' + node.name + ''
for attr, value of node.attribs
stack.push ' ' + attr + '="' + value + '"'
if node.name of emptyTags
stack.push '/>'
else
stack.push '>'
if node.children?
stack = stack.concat render(node.children)
stack.push '</' + node.name + '>'
return stack
module.exports = (dom) ->
stack = render(dom)
return stack.join('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment