Changing Text & HTML Content using Javascript

HTML DOM Property - textContent:

For older Browser:

To change the content of an HTML element, You can use the following syntax:
document.getElementById(id).textContent = new HTML

Source Code:
<html> 
<body> 
<p>Click the button & See the Result.</p> 
<button onclick="myFun()" id="btn">Here the Result</button> 
<p id="show_result"></p> 
</body> 
</html> 

<script> 
function myFun() { 
var input = document.getElementById("btn").textContent; document.getElementById("show_result").innerHTML = input; 
</script>

Result:

Here the Result

Note - textContent Property is not supported in Internet Explorer 8 and earlier.

Supported Browser:

  • Google Chrome 1.0
  • Internet Explorer 9.0
  • Mozila Firefox
  • Safari
  • Opera Mini

HTML DOM Property - innerHTML:

For modern Browser:

The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, You can use the following syntax:
document.getElementById(id).innerHTML = new HTML

Source Code:

<html> 
<body> 
<p id="text">This is a Simple Text.</p> 
<button onclick="myFun()">Check Result</button> 
<p id="show_result"></p> 
</body> 
</html> 
<script> 
function myFunction() { 
var input = document.getElementById("text").innerHTML; document.getElementById("show_result").innerHTML = input; 
</script>

Result:
This is a simple text.

Supported Browser:
  • Google Chrome
  • Internet Explorer
  • Mozila Firefox
  • Safari
  • Opera Mini
Similarity:
The "innerHTML" is similar to the "textContent" property.

Dis-Similarity:
There are some dissimilarity between innerHTML and textContent Property.

  • textContent returns the text content of all elements.
  • innerText returns the content of all elements, except for <script> and <style> elements.

In the following video, i'm showing How to change text and HTML content using innerHTML and textContent. I have also included the source code of the following video.
Source Code:
<html> 
<body> 
<h2>What Can JavaScript Do?</h2> 
<p id="showResult">Can Javascript Change Html Content?</p> 
<button type="button" onclick="myFunctionName();">Show Answer</button> 
</body> 
</html> 
<script type="text/javascript"> 
function myFunctionName(){ 
document.getElementById("showResult").innerHTML = "Yes ! Javascript can Change the HTML content"; 
</script>


EmoticonEmoticon