htmlparse
<html>
<head>
<style>
textarea{
width:800px;
height:250px;
}
</style>
<script>
/**
*Dom 类
*存储Dom树节点
*/
function Dom() {
this.tag = "";
this.attributes=[];// id class style name
this.innerHtml = "";
this.parent = "";
this.children=[];
this.num = 0;
this.cssNums =[];
this.each = function() {
}
}
/**
*HtmlParser类
*解析html文档
*/
function HtmlParser(html) {
this.parse = function(html,pDom) {
var dom = new Dom();
// 生成节点编号
dom.num = 1;
// 获取节点标签
dom.tag = this.getTag(html);
// 获取节点属性
dom.attributes = this.getAttributes(html);
// 获取节点innerHtml
dom.innerHtml = this.getInnerHtml(html);
// 生成节点父亲
dom.parent = pDom;
// 生成节点孩子 ==>如果innerHtml中有孩子,生成孩子,否则结束
if(this.isExistNode(dom.innerHtml)) {
var nodes = this.splitNodes(dom.innerHtml);
for (var i=0;i < nodes.length;i++) {
var childDom = this.parse(nodes[i],dom);
dom.children.push(childDom);
}
}
return dom;
};
// 获取节点的标签
this.getTag = function(html) {
var tag = "tag";
var tagStart = html.indexOf('<');
var spacePst = html.indexOf(' ',tagStart);
var rightPst = html.indexOf('>',tagStart);
var tagEnd = rightPst;
if (spacePst!=-1 && spacePst<rightPst) {
tagEnd = spacePst;
}
tag = html.substring(tagStart,tagEnd);
return tag;
}
// 获取节点的属性
this.getAttributes = function(html) {
var attributes = "attributes";
return attributes;
}
// 获取节点的innerHtml
this.getInnerHtml = function(html) {
var innerHtml = "innerHtml";
return innerHtml;
}
// 判断innerHtml 中是否有节点
this.isExistNode = function (html) {
return false;
}
// 将innerHtml 分割成孩子节点数组,必须保证里面有节点才能调用该函数
this.splitNodes = function (html) {
var nodes = [];
return nodes;
}
}
// 主函数
function main(){
var html = document.getElementById("content");
var htmlParser = new HtmlParser();
var dom = htmlParser.parse(html,"");
alert(dom.num + " " +dom.tag + " " + dom.attributes +" " +dom.innerHtml);
document.getElementById("result").value = dom;
}
</script>
</head>
<body>
<textarea id="content"></textarea>
<input type="button" value="转换" onclick="main()"/>
<textarea id="result"></textarea>
</body>
</html>