How to change an element in JavaScript?

To change or replace an element in javascript, you need to follow the steps below.

  1. Select the parent element of the target element.
  2. Now, change the parent element's value using the innerHTML property.

Example

<div id="my_div">
  <p>
    This is child element of the div element.
  </p>
</div>

In the above example, the <div> element is a parent element and the <p> element is the child element.

Select the parent element.

Use the getElementById() method to select that element.

Exmaple :

document.getElementById('my_div');

Change the child element.

We have already select the parent element. Inside the parent element, we have the child element. So, to change the child element, we have to use innerHTML property.

Example:

document.getElementById('my_div').innerHTML="<h2>Our new child element</h2>";

In the above example, I used the innerHTML property to change the <p> element.

Change element in js
<div id="my_div">
  <p>This is child element of the div element.</p>
</div>
<script>
  document.getElementById('my_div').innerHTML="<h2>Our new child element</h2>";
</script>
Try it Yourself »