您的位置:首页 > Web前端 > JavaScript

JS中innerHTML,innerText,outHTML的用法及区别

2015-07-16 09:09 836 查看
一张图解释:

对于一个id为"testdiv"的div来说,outerHTML、innerHTML以及innerTEXT三者的区别可以通过下图展示出来:



文字解释:

innerHTML,innerText,outHTML的用法及区别

<div id="seostudying"> <span style="color:red">www.seostudying.com</span> </div>

1.seostudying.innerText

它得到的是<div></div>标签中的文本节点的内容,也就是seostudying

2.seostudying.innerHTML

它得到的是<div></div>标签中的所有内容,包括元素节点,属性节点以及文本节点,也就是<span style="color:red">www.seostudying.com</span>

3.seostudying.outerHTML

它得到的是包括<div></div>标签自身及其中的所有内容,也就是<div id="seostudying"><span style="color:red">www.seostudying.com</span></div>

示例:

<span style="font-size:18px;"><div id="seostudying"><span style="color: red;">www.seostudying.com</span></div>
<style>
a{color:#ff0000; padding:5px 15px;}
</style>
<a  href='javascript:alert(document.getElementById("seostudying").innerText)'>innerText属性</a>;
<a  href='javascript:alert(document.getElementById("seostudying").innerHTML)'>innerHTML属性</a>;
<a  href='javascript:alert(document.getElementById("seostudying").outerHTML)'>outerHTML属性</a>;
</span>
<span style="font-size:18px;">
</span>

3、innertext兼容性

IE、Safari、Opera和Chrome支持innerText属性。Firefox虽然不支持innerText,但支持作用类似的textContent属性。textContent是DOM3级规定的一个属性,而且也得到了safari、opera和Chrome的支持。为了确保跨浏览器兼容,有必要想下面这样通过函数来检测可以使用哪个属性:

var div = document.getElementById("content");
function getInnerText(element) {
return (typeof element.textContent == "string") ? element.textContent : element.innerText;
}
function setInnerText(element, text) {
if (typeof element.textContent == "string") {
element.textContent = text;
} else {
element.innerText = text;
}
}
setInnerText(div, "Hello world!");
alert(getInnerText(div)); //"Hello world!"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: