InnerHTML and innerText Usages

 innerHTML is use to declare some element's inner HTML and innerText

The folowing playgronund shows the difference. Try type in some html code,such as h1, h2, or button tags to see effects.

innerHTML example

hi

innerText example

<h2>hi</h2>

Plauground Source Code

<textarea oninput="showhtml.innerHTML = this.value;showtext.innerText = this.value;"><h2>hi</h2></textarea>
<h3>innerHTML example</h3>
<div id="showhtml"><h2>hi</h2></div>
<h3>innerText example</h3>
<div id="showtext">&lt;h2&gt;hi&lt;/h2&gt;</div>
The idea is when you want to output html tags as the wording in the browser, use innerText. If you want to output the html elements, use innerHTML

The other thing is innerHTML and innerText show opposite results have you grab what is inside the tags. What I mean is when you want to output html in text, you use innerText, but when you want to grab the DOM elements' html in text, you use innerHTML.

Consider the folowing code to see why:
<div id = "example">
    <h3>inside text</h3>
</div>
<div id = "showexampletext"></div>
<div id = "showexamplehtml"></div>
<div id = "showexamplehtmlintext">
</div>
<script>
    showexampletext.innerHTML = example.innerText; 
    showexamplehtml.innerHTML = example.innerHTML; 
    showexamplehtmlintext.innerText = example.innerHTML;
</script>

Results:

Below is what is in <div id = "example"></div>, which is <h2>inside text</h2>

inside text

showexampletext:
showexamplehtml:
showexamplehtmlintext:

If you are lasy typing using &lt; for < and &gt; for > when editing html, you can also use the innerText to outpot it in the DOM.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser