在DOM中,如果要在一个标签上面加入文字,则必须用object.appendChild(document.createTextNode("你要加入的文字"));让人感觉非常麻烦,代码冗长,于是乎,就有了用object.innerText = "你要加入的文字";这一种写法.是代码更简洁,更易于理解.innerText会自动把大于号,小于号等等的HTML元素都进行编码,所以不必担心显示的问题,如果确实要用HTML方式的,请使用innerHTML.下面的代码摘自JS高级程序设计一书:
innerText:
<html>
<head>
<title>InnerText Example</title>
<style type="text/css">
div.special {
background-color: red;
padding: 10px;
}
</style>
<script type="text/javascript">
function useInnerText() {
var oDiv = document.getElementById("div1");
oDiv.innerText = oDiv.innerText;
}
</script>
</head>
<body>
<div id="div1" class="special"><b>Hello</b> world</div>
<input type="button" value="Use InnerText" οnclick="useInnerText()" />
<p><strong>Note: </strong> Firefox does not support the <code>innerText</code> property so this example will fail.</p>
</body>
</html>
innerHTML:
<html>
<head>
<title>InnerHTML Example</title>
<style type="text/css">
div.special {
background-color: red;
padding: 10px;
}
</style>
<script type="text/javascript">
function useInnerHTML() {
var oDiv = document.getElementById("div1");
oDiv.innerHTML = "<b>Hello</b> world";
}
</script>
</head>
<body>
<div id="div1" class="special">This is my original text</div>
<input type="button" value="Use InnerHTML" οnclick="useInnerHTML()" />
</body>
</html>
此外,我们还可以通过这2个属性来获取元素的内容: