How to Replace Content in Javascript

In this video tutorial, you will learn how to replace content in javascript. We are going to replace content on button click using innerhtml property and innertext property.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  
  <div class="container">
    <div>
      <button id="btnText">Text</button>
      <button id="btnHtml">HTML</button>
    </div>

    <div id="content">
      <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Consequatur, odio pariatur quam nostrum eos deleniti maiores rerum neque obcaecati similique est quae illo nihil fugiat enim eligendi ullam possimus labore?</p>
    </div>
  </div>

  <script src="script.js"></script>
</body>
</html>

 

CSS:

.container,#content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

#content {
    padding: 10px;
    margin-top: 10px;
    border: 1px solid black;
    width: 50%;
    min-height: 100px;
}

button {
    padding: 10px 20px;
    margin: 5px;
    outline: none;
}

 

Javascript:

let btnText = document.querySelector('#btnText');
let btnHtml = document.querySelector('#btnHtml');
let content = document.querySelector('#content');
let paragraph = document.querySelector('p');

btnText.addEventListener('click', () => {
    paragraph.innerText = 'Hello World';
});

btnHtml.addEventListener('click', () => {
    content.innerHTML = '<h1>Hello World</h1>';
});

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •