<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
window.onload = function(){
var s ="<html>\n"
+"<body>\n"
+" \n"
+"<div>\n"
+"123\n"
+" \n"
+"</div>\n"
+" \n"
+"</body>\n"
+" \n"
+"</html>"
var str = s.replace(/(\s+\n+|\n+|\s+|\n+\s+)/g,"")
console.log(str)
var str = str.replace(/></g,">\n<")
console.log(str)
var str = str.replace(/>\S+</g,function(world){
return ">\n"+world.substring(1,world.length-1)+"\n<"
})
console.log(str)
document.getElementById("msg").innerText = str
}
</script>
<style type="text/css">
.msg{
width: 100%
height: 60px
color:#FBBDEE
}
</style>
</head>
<body>
<div id="msg" class="msg"></div>
</body>
</html>
不知道适不适合你的要求。个人觉得是可以满足的。
取出两个undefined是因为在ff中,会将元素内的换行当成一个空的文本节点来处理。
有两种办法可以忽略掉空的文本节点:
第一种,根据nodeType过滤掉空文本节点:
function getFirstChild(parent) {if(parent && parent.nodeType == '1') {
var node = parent.firstChild
while(node.nodeType != 1) {
node = node.nextSibling
}
return node
}
}
第二种办法,用children[0]获取第一个节点,比如:
<div id="c">
<span>first span</span>
</div>
document.getElementById('c').children[0]取到的就是第一个span。
另外,children在IE中会将注释当作节点包含在内,需要注意一下,比如下面这种结构:
<div id="c">
<!-- this is comment -->
<span>Span<span>
</div>
在IE中使用document.getElementById('c').children[0],获取到的是<!-- this is comment -->,而不是<span>Span</span>。
nodeType返回值代表的含义:
返回值 节点类型
1 Element 元素节点
2 Attr 属性节点
3 Text 文本节点
4 CDATASection <![CDATA[]]>
5 EntityReference 文档中的实体引用部分
6 Entity 文档中的实体
7 ProcessingInstruction 处理指令
8 Comment 注释
9 Document 整个文档(文档根节点)
10 DocumentType 向为文档定义的实体提供接口
11 DocumentFragment 轻量级的 Document 对象,能够容纳文档的某个部分
12 Notation 代表 DTD 中声明的符号
各类节点的子节点:
节点类型 子节点类型
1 1、3、4、5、7、8
2 3、5
3 无子节点
4 无子节点
5 1、3、4、5、7、8
6 1、3、4、5、7、8
7 无子节点
8 无子节点
9 1、7、8、10
10 无子节点
11 1、3、4、5、7、8
12 无子节点