【JS兼容】获取元素内的文本

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<pre>
<p><span>a</span>b</p>
p元素节点((span元素节点(a文本节点,a文本节点的值是a))(b文本节点,b文本节点的值是b))
<div>c</div>
</pre>
<script>
function text(e){
    var t = "";
    e = e.childNodes || e;
    for (var j = 0; j < e.length; j++) {
        t += e[j].nodeType != 1 ? e[j].nodeValue : text(e[j].childNodes);
    }
    return t;
}
alert(text(document.getElementsByTagName("p")[0]));
//非Mozilla浏览器
alert(document.getElementsByTagName("div")[0].innerText);
//其他浏览器
alert(document.getElementsByTagName("div")[0].childNodes[0].nodeValue);
//如果你确定元素只包含文本,innerHTML方法可取代text方法
alert(document.getElementsByTagName("div")[0].innerHTML);
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/jzm17173/p/2493574.html