In javascript, if we want to obtain the object content, js provides three methods for us: outerhtml, innerhtml, and innertext. But what is the difference between them and their specific usage, A lot of people may not know how to use innerHTML, innerText, and outerHTML. No nonsense. Please refer to the following example.
Usage:
test1 test2
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"Test1 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
test1 test2
Complete example:
Test1 test2
InnerHTML content inerHTML content outerHTML content
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:
/Gim, '')"> no html, compliant with W3C standards
How can I differentiate innerHTML and innerText?
Sample Code:
Test1 test2
InnerHTML content inerHTML content
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 "test1 ".
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.