I am writing a JavaScript function which can tidy up HTML code (JavaScript and CSS code tidying is not necessary at the moment).
Here is my code. And check it on http://jsfiddle.net/2q26K/
function tidyHtml(html) {
var html = html.trim().replace(/>[^<]+</gm, function ($1) {
return '>' + $1.substr(1, $1.length - 2).trim() + '<';
}).replace(/>\s+</gm, '><');
var containerElement = document.createElement('div');
containerElement.innerHTML = html;
var result = containerElement.innerHTML;
var findLevel = function (child, parent) {
var level = 0;
while (child != parent) {
child = child.parentNode;
level++;
}
return level;
}
Array.prototype.slice.call(containerElement.getElementsByTagName('*')).forEach(function (element) {
var tabs = new Array(findLevel(element, containerElement) - 1).join(' '),
tabs2 = (element.parentNode.lastChild == element) ? ('\n' + tabs.substring(0, tabs.length - 1)) : '',
containerElement = document.createElement('div');
containerElement.appendChild(element.cloneNode(true));
result = result.replace(containerElement.innerHTML, '\n' + tabs + containerElement.innerHTML + tabs2);
});
return result;
}
In the example provided, it works perfectly.
But, sometimes when HTML code is like that: http://jsfiddle.net/2q26K/1/
It refuses to change
<div id="hlogo">
<a href="/">Stack Overflow</a>ABC</div>
To
<div id="hlogo">
<a href="/">Stack Overflow</a>ABC
</div>
I cannot solve it. It's too complicated. Is there an easier method that can do the same thing?
How can I improve my code? What would be an example that I can learn from?