innerhtml and innertext are two properties in the JavaScript element object. Both can set or get the text content of the document object, but there are still some differences between the two. The following article will take you to understand the innerhtml and innertext properties, briefly compare innerhtml and innertext, and see what the difference is between the two.
First of all, let’s take a brief look at the innerHTML and innerText attributes; then use code examples to intuitively feel the difference between innerHTML and innerText attributes. [Recommended learning: javascript advanced tutorial]
innerHTML attribute: You can set or get the entire content from the starting position to the ending position of the tag
innerText attribute: You can set or get all the text information from the starting position to the ending position of the label
Describing through text, is it a bit confusing? Let’s take a look at a picture
Through the above picture, do we know the difference between innerhtml and innertext attributes? Let’s take a closer look at the difference between innerhtml and innertext attributes through code examples:
First we have this HTML framework
<div id="test"> <span style="color:red">test1</span> test2 </div> <input type="button" onclick="getContent()" value="获取div元素的内容"/>
We use the innerHTML attribute to get the content in the div tag
<script type="text/javascript"> function getContent(){ var div=document.getElementById("test"); console.log(div.innerHTML); } </script>
Click the button, Console output:
We use the innerText attribute to get the content in the div tag
<script type="text/javascript"> function getContent(){ var div=document.getElementById("test"); console.log(div.innerText); } </script>
Click the button, console output :
Summary: The difference between innerHTML and innerText attributes
The innerText attribute can output the plain text information between tags, and the tags will be Filtered.
The innerHTML attribute can output all the content between tags, including the HTML tags and text information inside.
Special note:
innerHTML is an attribute that complies with W3C standards, while innerText is only applicable to IE browsers, so innerText should be used sparingly.
If you must output content without HTML tags, you can first use innerHTML to obtain the content containing HTML tags, and then use regular expressions to filter HTML tags.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of What are the differences between innerhtml and innertext? A simple comparison between the two. For more information, please follow other related articles on the PHP Chinese website!