The js-beautify tool can work with html, and has an api. It's probably the easiest way to do what you want.
After installing it with node:
var beautify_html = require('js-beautify').html;
result = beautify_html(htmlstring);
To use it in a browser, you need to include all the beautify*.js scripts in this directory and use window.html_beautify
.
DEMO