<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple DOM example</title>
<style type="text/css"></style>
<style type="text/css"></style>
<script type="text/javascript"></script>
</head>
<body>
<div class="text-field">
<textarea id="textHTML" style="width: 100%;height: 500px;display: flex;margin: 0;"></textarea>
<button type="button" class="btn">格式化</button>
</div>
<div>
<div>
<p>
<a href=""></a>
</p>
</div>
</div>
<div class="行内元素中包裹块级元素">
<a href="">
<span>
<div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</span>
</a>
</div>
<asd></asd>
<div style="display: none;" class="ohtml"></div>
<script type="text/javascript">
(function(opt) {
function DomFormat(opt) {
this.el = opt && opt.el || document.getElementsByTagName('html')[0]; //建议直接获取html元素
this.isShowProperty = opt && opt.isShowProperty || true; //是否显示属性信息
this.isShowNodes = opt && opt.isShowNodes || true; //是否不判断nodeType true:只打印元素节点 false是所有节点
this.render();
}
DomFormat.prototype = {
genDomTree: function(oEle, list) {
var items = oEle.childNodes,
lists = list || '-' + oEle.nodeName.toLowerCase(),
oNbsp = "\n";
// 当前元素是html(el)元素的第几层子节点
var func = function(el) {
var count = 0,
parent = el.parentNode;
while (parent) {
parent = parent.parentNode;
count += 1;
}
return count;
}
for (var i = 0; i < func(oEle); i++) {
oNbsp += '-------+';
}
oNbsp += ' ';
for (var i = 0; i < items.length; i++) {
if (this.isShowNodes) {
if (this.isShowProperty) {
if (items[i].nodeType == 1) {
if (items[i].attributes.length) { //当前元素的属性
var temp = oNbsp + items[i].nodeName.toLowerCase() + ':Property ';
for (var j = 0; j < items[i].attributes.length; j++) {
temp += ' ' + (j + 1) + '. ' + items[i].attributes[j].name + '="' +
items[i].attributes[j].value + '" ';
}
lists += this.genDomTree(items[i], temp);
} else {
lists += this.genDomTree(items[i], oNbsp + items[i].nodeName
.toLowerCase());
}
}
} else {
if (items[i].nodeType == 1) {
lists += this.genDomTree(items[i], oNbsp + items[i].nodeName.toLowerCase());
}
}
} else {
if (this.isShowProperty) {
if (items[i].attributes.length) {
var temp = oNbsp + items[i].nodeName.toLowerCase() + ':Property ';
for (var j = 0; j < items[i].attributes.length; j++) {
temp += ' ' + (j + 1) + '. ' + items[i].attributes[j].name + '="' +
items[i].attributes[j].value + '" ';
}
lists += this.genDomTree(items[i], temp);
} else {
lists += this.genDomTree(items[i], oNbsp + items[i].nodeName
.toLowerCase());
}
} else {
lists += this.genDomTree(items[i], oNbsp + items[i].nodeName
.toLowerCase());
}
}
}
oNbsp = "\n";
return lists;
},
render: function() {
console.log(this.genDomTree(this.el));
}
}
window.DomFormat = DomFormat;
})();
var domFormat = new DomFormat();
</script>
</body>
</html>