by Sai gowtham

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>`

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course