The difference between JavaScript innerHTML and innerText



 JavaScript’s innerHTML and innerText look similar, but in fact there is a big difference. Most designers should be familiar with innerHTML. It is the syntax used to obtain HTML elements or write strings into HTML web pages, and innerHTML is W3C stipulates the standard writing method, and innerText can not only be used to obtain HTML elements, but also removes the HTML tags of the elements. However, innerText is not a standard writing method prescribed by the W3C and is only applicable to IE browsers. Very important.


JavaScript innerHTML and innerText basic syntax
HTMLDOMObject.innerText、HTMLDOMObject.innerText
The basic grammar of the two is very similar in principle, the difference lies in the result of operation.

JavaScript innerHTML and innerText examples
<script type="text/javascript">
function ChangeFontColor(){
    var OriginalFont_1=document.getElementById("StringFont_1").innerHTML;
    var OriginalFont_2=document.getElementById("StringFont_2").innerText;
    document.getElementById("StringFont_1" ).innerHTML='<font color="blue">'+OriginalFont_1+'</font>';
    document.getElementById("StringFont_2").innerHTML=OriginalFont_2;
}
</script>
<p id="StringFont_1">through innerHTML turns text into blue</p>
<p id="StringFont_2"><font color='blue'>Through innerText turns text into black</font></p>
<input type="button" value ="Change text color" onclick="ChangeFontColor()">
The output of the above example

Turn text to blue through innerHTML

Turn text to black through innerText

The first string of the example is black by default, and the tag containing the HTML font text color modification is written into the original position through innerHTML , and the string is modified to blue. The second string is originally blue, and the original is obtained through innerText After stringing, rewrite back to the original position. Since the HTML tags "<font color='blue'>" and "</font>" that originally controlled the text in blue are filtered out, the rewritten text is Become black. Please note that the second string color modification will have an effect only if you use IE browser. Using other browsers will display undefined. This example shows the main difference between innerHTML and innerText . 

Post a Comment

0 Comments