如何整理基于JavaScript的HTML代码 [英] How to tidy up HTML code based on JavaScript
问题描述
我正在编写一个可以整理HTML代码的JavaScript函数(目前无需整理JavaScript和CSS代码).
I am writing a JavaScript function which can tidy up HTML code (JavaScript and CSS code tidying is not necessary at the moment).
这是我的代码.并在 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.
但是,有时,当HTML代码是这样的时候: http://jsfiddle.net/2q26K/1/
But, sometimes when HTML code is like that: http://jsfiddle.net/2q26K/1/
它拒绝更改
<div id="hlogo">
<a href="/">Stack Overflow</a>ABC</div>
收件人
<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?
推荐答案
如果速度不是问题,则可以运行jQuery解析器(或者 Cheerio 和 Node.js ) HTML字符串,使用$(String).html()方法如此处所述.
If speed is not an issue, you could run a jQuery parser (alternatively Cheerio with Node.js) on your generated HTML string, using the $(String).html() method as explained here.
这篇关于如何整理基于JavaScript的HTML代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!