coding180 icon
Coding180
JavaScript innerHTML attribute

JavaScript innerHTML attribute

Home > Tutorials > JavaScript > DOM Manipulation


The innerHTML property is used to get or replace the content of an HTML element.

Syntax:

Object.innerHTML

Notice:

  1. Object is the obtained element object, such as the element obtained through document.getElementById("ID").
  2. Pay attention to writing, innerHTML is case sensitive.

We get the <p> element through id="con", and output and change the content of the element, the code is as follows:

<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS innerHTML - coding180.com </title>

</head>

<body>
    <p id="con">Hello world</p>

    <script type="text/javascript">
        // refrence p tag using its id
        var con = document.getElementById('con');
        document.write("Unmodified content: " + con.innerHTML + "<br/>");

        // modify content
        con.innerHTML = "New text";
        document.write("Modified content: " + con.innerHTML + "<br/>"); 
    </script>
</body>

</html>

result:

innerHTML attribute javascript

Task - Exercise - 18

1. complete the code on line 13, to get the h2 tag element id and assign it to the variable mychar.

2. Supply code to line 17, use the innerHTML attribute to modify the obtained h2 tag content to "Hello world!"

Task Code

<!DOCTYPE HTML>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>innerHTML - coding180.com</title>
</head>

<body>
    <h2 id="con">First Text</H2>
    <script type="text/javascript">
        // get h2 tag id
        var mychar ;

        // print first text
        document.write("Data: " + mychar.innerHTML + "<br>");

        // print updated text
        document.write("Updated Data: " + mychar.innerHTML); 
    </script>
</body>

</html>

 


user

Robort Gabriel

Lagos, Nigeria

Freelance Web Developer, Native Android Developer, and Coding Tutor.

Skills
  • UI / UX
  • JavaScript
  • Python
  • PHP
  • Kotlin
  • Java
  • Bootrap
  • Android
  • Laravel