JavaScript加油站 1-innerHTML与innerText的用法与区别

摘自 鱼有所思的博客 http://www.phpweblog.net/kiyone/archive/2007/05/17/1206.aspx

用法:

<div >

<span >test1</span> test2

</div>

在JS中可以使用:

test.innerHTML:

  也就是从对象的起始位置到终止位置的全部内容,包括Html标签。

  上例中的test.innerHTML的值也就是“<span >test1</span> test2 ”。

test.innerText:

  从起始位置到终止位置的内容, 但它去除Html标签

  上例中的text.innerTest的值也就是“test1 test2”, 其中span标签去除了。

test.outerHTML:

  除了包含innerHTML的全部内容外, 还包含对象标签本身。

  上例中的text.outerHTML的值也就是<div >test1</span> test2</div>

完整示例:

<div >

<span >test1</span> test2

</div>

<a href="javascript:alert(test.innerHTML)">innerHTML内容</a>

<a href="javascript:alert(test.innerText)">inerText内容</a>

<a href="javascript:alert(test.outerHTML)">outerHTML内容</a>

特别说明:

  innerHTML是符合W3C标准的属性,而innerText只适用于IE浏览器,因此,尽可能地去使 用innerHTML,而少用innerText,如果要输出不含HTML标签的内容,可以使用innerHTML取得包含HTML标签的内容后,再用正 则表达式去除HTML标签,下面是一个简单的符合W3C标准的示例:

<a href="javascript:alert(document.getElementById('test').innerHTML.replace(/<.+?>/gim,''))">无HTML,符合W3C标准</a>

-------------------------------------------------------------------------------------------------------------------------------

<html>

<head></head>

<frameset frame frame rows="40%,*">

<frame name="top" src="1.html">

<frame name="bottom" src="2.html">

</frameset>

</html>

<html>

<head>

<script language="javascript">

function init()

{

var aaa = parent.window.frames[0].document.body.innerHTML;

alert(aaa);

}

</script>

</head>

<body>

<p align="center">nothing</p>

<p align="center"><input type="button" onclick="init()"; value="click"></p>

</body>

</html>

<html>

<center>汽车 房产 女人</center>

</html>