Javascript: The getElementById() method

This entry is part 11 of 27 in the series Javascript Tutorial

The getElementById() method accesses the element with the specified id.

An id can be assigned to a particular HTML element such as <p> or <h1>.

<!DOCTYPE html>
<html>
<head>
 <title>Variables</title>
 <script>
   function updateFunction()
    {
      var new_str = "I am a new string";
      var new_int = 15;
      document.getElementById("str1").innerHTML=new_str;
      document.getElementById("int1").innerHTML=new_int;
    }
 </script>
</head>
<body>
 <h4 id="str1">I am a string</h4>
 <p id="int1">I will be an integer</p>
 <br>
 <button onclick="updateFunction()">Click Me</button>
 </body>
</html>

button

In the example above, an id=”str1″ and an id=”int1″ have been assigned to elements <h4> and <p>.

We can use similar method getElementById() to update the content inside both of the tags.

      document.getElementById("str1").innerHTML=new_str;
      document.getElementById("int1").innerHTML=new_int;

 

Series Navigation<< Javascript: Global variables
Javacript: Integer variables >>