JavaScript

How to change the text inside a DIV element in JavaScript

In this tutorial, we are going to see how to change the content of an HTML element, for example <p>, <div>, <span>, etc. In the example below, we will use the <div> tag as an example. There are two methods to get and change the content of an HTML element, either using the textContent or innerText property.
 

Method 1: Using the textContent property
<html>
   <body>
      <div id="myDiv">Welcom to StackHowTo!</div>
   </body>
   <script type="text/javascript">
     var text = document.getElementById('myDiv').textContent = "Hello World!";
     alert(text);
   </script>
</html>

Output:

Hello World!
 

Method 2: Using the innerText property
<html>
   <body>
      <div id="myDiv">Welcom to StackHowTo!</div>
   </body>
   <script type="text/javascript">
    var text = document.getElementById('myDiv').innerText = "Hello World!";
    alert(text);
   </script>
</html>

Output:

Hello World!
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *