The usage and difference of innerHTML, innerText, and outerHTML in JavaScript, innerhtmlouterhtml
No nonsense. Please refer to the following example.
Usage:
<div id="test"> <span style="color:red">test1</span> test2 </div>
In JS, you can use:
Test. innerHTML:
That is, all content from the starting position of the object to the ending position, including Html tags.
In the above exampleTest. innerHTMLThe value is"<Span style =" color: red "> test1 </span> test2 ".
Test. innerText:
Content from the starting position to the ending position, but it removes the Html Tag
In the preceding example, the value of text. innerTest is "test1 test2", in which the span tag is removed.
Test. outerHTML:
In addition to all the content of innerHTML, it also contains the object tag itself.
In the preceding example, the value of text. outerHTML is
<div id="test"><span style="color:red">test1</span> test2</div>
Complete example:
<Div id = "test"> <span style = "color: red"> test1 </span> test2 </div> <a href = "javascript: alert (test. innerHTML) "> innerHTML content </a> <a href =" javascript: alert (test. innerText) "> inerHTML content </a> <a href =" javascript: alert (test. outerHTML) "> outerHTML content </a>
Note:
InnerHTML is a W3C standard attribute, while innerText is only applicable to IE browsers. Therefore, use innerHTML as much as possible, instead of innerText. If you want to output content without HTML tags, you can use innerHTML to obtain the content containing HTML tags and use regular expressions to remove HTML tags. The following is a simple W3C-compliant example:
<A href = "javascript: alert (document. getElementById ('test'). innerHTML. replace (/<. ++?> /Gim, '')"> no html, compliant with W3C standards </a>
How can I differentiate innerHTML and innerText?
Sample Code:
<Div id = "test"> <span style = "color: red"> test1 </span> test2 </div> <a href = "javascript: alert (test. innerHTML) "> innerHTML content </a> <a href =" javascript: alert (test. innerText) "> inerHTML content </a>
Commonalities:InnerHTML and innerTextWill replace the content in the element.
Differences:
1, innerHTML:
That is, all content from the starting position of the object to the ending position, including Html tags.
In the preceding example, the value of test. innerHTML is <span style = "color: red"> test1 </span>.
Test2 ".
2, innerText:
Content from the starting position to the ending position, but it removes the Html Tag
In the preceding example, the value of text. innerTest is "test1 test2", in which the span tag is removed.
It is worth noting that innerHTML is a W3C standard attribute, while innerText is only applicable to IE browsers. Therefore, try to use innerHTML instead of innerText. If you want to output content without HTML tags, you can use innerHTML to obtain the content containing HTML tags, and then use a regular expression to remove HTML tags.
The preceding section describes the usage and differences of innerHTML, innerText, and outerHTML in JavaScript.