Node.prototype.textContent

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Document</title> 
</head> 
<body> 
    <div id="test">hello<span>world</span></div> 
    <script> 
        var test = document.getElementById('test'); 
        console.log(test.nodeValue); 
        console.log(test.firstChild.nodeValue); 
        console.log(test.textContent); 
        console.log(test.firstChild.textContent); 
    </script> 
</body> 
</html>

nodeValue 只获取当前节点的文本值, 如果节点类型不是文本 /属性 / 注释, 则会返回null. 

textContent 获取当前节点及其所有后代节点的文本值, 没有获取到, 则返回一个空字符串.

 

文档节点(document) 和 文档类型节点(doctype) 的textConent是一个空字符串, 如果想获取document的文本值(即整个网页文本) 可以通过 document.documentElement.textContent 获取

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

怎样获取节点的文本值