JavaScript innerHTML

In JavaScript, innerHTML refers to the content of an HTML element. Therefore, the innerHTML property sets/returns content to/of specified HTML element. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>The value is <span id="x"></span></p>
   
   <script>
      var element = document.getElementById("x");
      element.innerHTML = 10;
   </script>
   
</body>
</html>
Output

The value is

In above example, the following statement:

var element = document.getElementById("x");

is used to initialize the element whose ID value is x to element variable. And using the following statement:

element.innerHTML = 10;

The value 10 set as the content of returned element. In case, if the returned element already has some content, then the content will be removed and the new content using the innerHTML will get set to it.

To set/get the content of an HTML element using the innerHTML property, we need to get the element using any of the following methods:

JavaScript innerHTML Syntax

The syntax of innerHTML property in JavaScript, is:

element.innerHTML

JavaScript innerHTML Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="cc">The name of website is: codescracker.com</p>
   <p>The content of P tag, with cc as its ID value is:
   <span id="res"></span></p>
   
   <script>
      content = document.getElementById("cc").innerHTML;
      element = document.getElementById("res");
      element.innerHTML = content;
   </script>
   
</body>
</html>
Output

The name of website is: codescracker.com

The content of P tag, with cc as its ID value is:

The above example, can also be written as:

<!DOCTYPE html>
<html>
<body>

   <p id="cc">The name of website is: codescracker.com</p>
   <p>The content of P tag, with cc as its ID value is:
   <span id="res"></span></p>
   
   <script>
      document.getElementById("res").innerHTML = document.getElementById("cc").innerHTML;
   </script>
   
</body>
</html>

In above example, the following JavaScript code:

document.getElementById("cc").innerHTML

returns the content of an HTML element, whose ID value is cc. And this content will be initialized to an HTML element whose ID value is res.

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this article? Share it!





Like/follow us on social media for updates!