javascript获取元素文本内容的通用函数

  作者:bea

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>一个获取元素文本内容的通用函数</title>
</head>
<body>
<p id="p1">中华人民共和国<b>1</b> <span>2</span></p>
</body>
<script language="javascript"><!--
//一个获取元素文本内容的通用函数
function text(e){
var t="";
e=e.childNodes || e;//如果传入的是元素,则继续遍历其子元素;否则假定它是一个数组
for(var i=0;i<e.length;i++){
//如果不是元素,追回其文本值;
//否则,递归遍历所有元素的子节点;
t += e[i].nodeType != 1 ? e[i].nodeValue : text(e[i].childNodes);
}
return t;
}
var p1=document.getElementById("p1");
alert(text(p1)); //返回中华人民共和国 1 2
alert(text(p1.lastChild)); // 返回2
alert(text(p1.firstChild.nextSibling));//返回1
// --></script>
</html>




[Ctrl+A 全选 注:
如需引入外部Js需刷新才能执行]

将HTML DOM中几个容易常用的属性做下记录:

nodeName、nodeValue 以及 nodeType 包含有关于节点的信息。
nodeName 属性含有某个节点的名称。

元素节点的 nodeName 是标签名称
属性节点的 nodeName 是属性名称
文本节点的 nodeName 永远是 #text
文档节点的 nodeName 永远是 #document
注释:nodeName 所包含的 XML 元素的标签名称永远是大写的

nodeValue
对于文本节点,nodeValue 属性包含文本。

对于属性节点,nodeValue 属性包含属性值。

nodeValue 属性对于文档节点和元素节点是不可用的。

nodeType
nodeType 属性可返回节点的类型。

最重要的节点类型是:

元素类型 ==》节点类型
元素element ==》1
属性attr ==》2
文本text ==》3
注释comments ==》8
文档document ==》 9


有用  |  无用

猜你喜欢