HTML DOM对象的textContent属性用于设置或返回指定节点及其所有后代的文本内容。此属性与nodeValue属性非常相似,但此属性返回所有子节点的文本。
textContent属性的使用
语法:
● 用于设置节点的文本:
node.textContent = text
● 用于返回节点的文本
node.textContent
属性值:包含单值文本,其中包含节点的节点内容。
示例1:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="hello">Hello world!</h1>
<button onclick="Hello()">单击此处,返回节点的文本 </button>
<p id="sudo"></p>
<script>
function Hello() {
var text = document.getElementById("hello").textContent;
document.getElementById("sudo").innerHTML = text;
}
</script>
</body>
</html>
效果图:
示例2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="hello">Hello world!</h1>
<button onclick="Hello()">单击此处,设置节点的文本 </button>
<p id="sudo"></p>
<script>
function Hello() {
document.getElementById("hello").textContent
= "You're welcome!";
}
</script>
</body>
</html>
效果图:
浏览器支持
textContent属性支持的浏览器如下所示:
● Chrome 1.0
● Internet Explorer 9.0
● Firefox
● Safari
● Opera
推荐阅读: