JavaScript getElementById div

This page discusses - JavaScript getElementById div

JavaScript getElementById div

JavaScript getElementById div

        

In JavaScript we can get access to any node by using the method document.getElementById(). This method is very important for the JavaScript and is the entry point of the DOM (Document Object Model) scripting. Here in the following example we have used document.getElementById() method to get access to a div element.

Description of code :

This example illustrates the use of getElementById() method on a div element. We have created a div with the id "myDiv", a button named "Move text to div" and one text field. Button when clicked it moves the input text field value to the div. When we click on the button it calls the user defined function sendText(). Defined function is as follows :

 function sendText() {
	var txtValue = document.getElementById('txt').value;
	document.getElementById('myDiv').innerText = txtValue;
 }

First line of the function gets the input text field value into a variable "txtValue" and in the second line we have placed this received text value to the div content by applying the innerText property over the "div" reference.

Full example code of getElementByIdDiv.html is as follows :

<html>
  <head>
    <title>
      getElementById Div example
    </title>
     <script language="javascript" >
      function sendText() {
	var txtValue = document.getElementById('txt').value;
	document.getElementById('myDiv').innerText = txtValue;
      }
     </script>
   </head>
   <body>
     <div style="background: #DFDFFF; width:'100%';" align="center">
       <font color="#000080" size="12pt">
	<b>getElementById in &lt;div&gt;</b>
       </font>
     </div>
     <p>&nbsp;</p>
	<div id="myDiv" style="background:#ffffdd; height:100px;">
	</div>
     <p>&nbsp;</p>
     <center>
	<input type="text" id="txt" size="55">
	<input type="button" value="Move text to div" 
             onClick="sendText();" />
     </center>
   </body>
</html>

Output :

Output would be like as given above. Now input some text into text field to set it into div.

Click on the button "Move text to div"

Download Source Code