Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Javascript Javascriptexamples JavaScript getElementById innerHTML

Related Tutorials


 
 

Share on Google+Share on Google+

JavaScript getElementById innerHTML

Advertisement
This page discusses - JavaScript getElementById innerHTML

JavaScript getElementById innerHTML

       

In JavaScript method document.getElementById() is very useful for containing any element reference. We can handle the properties of element by having once the element's reference. In this example we have to show the use of innerHTML attribute property with getElementById() method. 

To show use of both we have created a simple HTML page into which we are going to add one select box with three of it's options. For this purpose we have added a button into the HTML page it calls the method addOptions() on the click event.


 function addOptions() {

 var txtValue = '<select style="width:150px;">
   <option>
1</option>
   <option>
2</option>
   <option>
3</option>
   </select>
';
 document.getElementById('myDiv').innerHTML= txtValue;
 }

In the very first line of code we have held  the HTML code as a string format into a variable txtValue and in the second line of code we have first taken the "myDiv" element's reference and after having reference we will assign the value of variable "txtValue" into the myDiv's inner code with line :

document.getElementById('myDiv').innerHTML= txtValue;

Here is the full example HTML code as follows :


<html>

  <head>
  <title>
 getElementById innterHTML example
  </title>
  
  <script language="javascript" >
  function addOptions() {
 var txtValue = '<select style="width:150px;">
    <option>
1</option>
    <option>
2</option>
    <option>
3</option>
   </select>
';
 document.getElementById('myDiv').innerHTML= txtValue;
  }
  </script>
  </head>
  <body>
  <div style="background: #DFDFFF; width:'100%';" align="center">
  <font color="#000080" size="12pt">
  <b>getElementById in &lt;innerHTML&gt;</b>
  </font>
  </div>
  <p>&nbsp;</p>
  <div id="myDiv" style="background:#ffffdd; height:100px;">
  </div>
  <p>&nbsp;</p>
  <center>
  <input type="button" value="Add Options" onClick="addOptions();" />
  </center>
  </body>
</html>

Output :

As soon as you will click on the "Add Option" button it will generate the HTML code and will add this code into the div with help of innerHTML attribute property.

Download Source Code

       

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 18, 2011

Related Tutorials

Discuss: JavaScript getElementById innerHTML  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com