Difference between innerText and innerHTML in JavaScript
In this tutorial, we are going to learn about the difference bettween innerText and innerHTML properties in JavaScript.
innerText
The innerText property is used to sets or gets the text from an element.
Consider we have a p
element with some text.
<p id="short">Welcome to happy world</p>
Now, if we call a innerText
property on p
element we will get the text present inside a <p>
element.
const p = document.getElementById('short');
const text = p.innerText;
// getting text
console.log(text); // Welcome to happy world
// setting new text
p.innerText = "you can see me";
innerHTML
The innerHTML property is used to sets or gets the html from an element.
Example:
<div id="box">
<h1>My first post</h1>
<p>Some text</p>
</div>
Now, if we call a innerHTML
property on div
element we will get the html present inside a <div>
element.
const div = document.getElementById('box');
// getting Html
const html = div.innerHTML;
console.log(html);
Output:
"
<h1>My first post</h1>
<p>Some text</p>
"
Setting Html
We can replace the div
element existing html content with a new html by setting the value of innerHTML
.
const div = document.getElementById('box');
// setting Html
div.innerHTML = `<h2>How to enjoy</h2>
<button>Click me</button>`