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
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- IE和Firefox下event事件杂谈
- div+css+js模拟tab切换效果 事件绑定 IE,firefox兼容
- 替代window.event.srcElement效果的可兼容性的函数
- JavaScript 序列化对象实现代码
- 让div层随鼠标移动的实现代码 ie ff
- Javascript 多浏览器兼容性问题及解决方案
- Javascript在IE或Firefox下获取鼠标位置的代码
- javascript DOM操作之动态删除TABLE多行
- javascript 导出数据到Excel(处理table中的元素)
- event.srcElement 用法笔记e.target
- javascript获得光标所在的文本框(text/textarea)中的位置
- [原创]javascript 移动鼠标得到单元格所在table表中的rowIndex位置[兼容ie,firefox]
- Javascript document.referrer判断访客来源网址
- jQuery Attributes(属性)的使用(二、类篇)
- textbox 在光标位置插入字符功能的js实现(兼容ie,firefox)
- Javascript 中介者模式实例
- js textarea自动增高并隐藏滚动条
- jquery 简单的图片展示效果
- javascript 动态设置已知select的option的value值的代码