Home > Web Front-end > JS Tutorial > body text

The difference between javascript innerHTML, outerHTML, innerText and outerText_javascript skills

WBOY
Release: 2016-05-16 18:58:10
Original
982 people have browsed it

1. Function explanation:
innerHTML sets or gets the HTML located within the opening and closing tags of the object
outerHTML sets or gets the HTML form of the object and its content
innerText sets or gets the text located within the start and end tags of the object
outerText sets (including labels) or gets (excluding labels) the text of the object
2. Example

<html> 
<head> 
<title>Demo</title> 
<style><!-- 
body {font-family:"宋体";color="blue";font-size="9pt"} 
--> </style> 
<script language="JavaScript"> 
//.innerHTML 
function innerHTMLDemo() 
{ 
test_id1.innerHTML="<i><u>设置或获取位于对象起始和结束标签内的 HTML.</u></i>"; 
} 
//.innerText 
function innerTextDemo() 
{ 
test_id2.innerText="<i><u>设置或获取位于对象起始和结束标签内的文本.</u></i>"; 
} 
//.outerHTML 
function outerHTMLDemo() 
{ 
test_id3.outerHTML="<i><u>设置或获取对象及其内容的 HTML 形式.</u></i>"; 
} 
//.outerText 
function outerTextDemo() 
{ 
test_id4.outerText="<i><u>设置(包括标签)或获取(不包括标签)对象的文本.</u></i>"; 
} 
</script> 
</head> 
<body> 
<ul> 
<li id="test_id1" onclick="innerHTMLDemo()">innerHTML效果.</li> 
<li id="test_id2" onclick="innerTextDemo()">innerText效果.</li> 
<li id="test_id3" onclick="outerHTMLDemo()">outerHTML效果.</li> 
<li id="test_id4" onclick="outerTextDemo()">outerText效果.</li> 
</ul> 
</body> 
</html> 
Copy after login

3. Differences:
To put it simply, the differences between innerHTML and outerHTML, innerText and outerText are:
1) The HTML contained in innerHTML and outerHTML will be parsed when setting the content of the object, but innerText and outerText will not.
2) When setting, innerHTML and innerText only set the text within the tag, while outerHTML and outerText set the text including the tag.

Special instructions:
innerHTML is an attribute that complies with W3C standards, and innerText is only applicable to IE browsers. Therefore, use innerHTML as much as possible and innerText less. If you want to output content that does not contain HTML tags, you can use innerHTML to obtain content that contains HTML tags. Finally, use regular expressions to remove HTML tags. Here is a simple example that complies with W3C standards:

<a href="javascript:alert(document.getElementById('test').innerHTML.replace(/<.+&#63;>/gim,''))">无HTML,符合W3C标准</a>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!