HomeTutorsContact

How to replace inner html with JavaScript?

By Gulshan Saini
Published in JavaScript
May 29, 2020
1 min read

In this quick tutorial I am going to show you how you can replace inner html contents of any element using property element.innerHTML

Tip: You can even use element.innerHTML to get markup of any element

Let’s start with following markup

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Replace Inner HTML of Element</title>
  </head>
  <body>
    <div id="main">
      <p>Replace me!!</p>
    </div>
  </body>
</html>

Now, we are going to replace following paragraph element

<p>Replace me>!!</p>

with following h2 element

<h2>Section replaced dynamically!!</h2>

First, we need to get the reference of parent element, which is <div id="main"> in our case

// get handle of parent element whose contents need to be replaced let element =
document.querySelector('#main');

Next, we can to set the inner html as follows

// get handle of parent element whose contents need to be replaced let element =
document.querySelector('#main'); element.innerHTML = '
<h2>Section replaced dynamically!!</h2>
';

Output

Summary

  • The element.innerHTML can be used to get or set inner html of eny element

Tags

#dom-manipulation
Previous Article
How to create elements dynamically in Javascript?

Related Posts

JavaScript
How to iterate through NodeList using Javascript?
July 09, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media