Element.innerHTML property to set
, or get
element's HTML code.
Ex: We have a <h1>
tag and strong style with it:
<h1 id="myHeader" style="color: green"><strong>My Header</strong> Normal Text</h1>
To get
content of the element has id equals to "myHeader", we will do the same:
var element = document.getElementById("myHeader");
element.innerHTML
Return result:
<strong>My Header</strong> Normal Text`
To "set" new content (value) for this element, the code will be here:
Element.innerHTML = "My Header My Text";
So this property not only works with plain text, but it is aimed at passing or copying HTML code.
=> We should not use it.
However, many programmers (including myself) use this attribute to insert text into a web page, and this method carries a potential risk:
- Wrong operation: inserting each text only sometimes deletes all other HTML code of the inserted element.
- For security: Of course, the two examples above are completely harmless, even if using the tag is still no problem because the HTML5 standard has prevented the execution of the command line inside the tag. when inserted into the web page via the innerHTML attribute. See this rule here.
Because of this reason, using innerHTML
is not recommended when inserting plain text, instead use textContent
. The textContent
property will not understand that the code you pass is an HTML syntax, but just a 100% text no more and no less.
The result returns if using textContent
in the above example:
My Header My Text