Home Javascript JavaScript getElementById method
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

JavaScript getElementById method

Advertisement
We can access the specific element of any existing html page by using the method getElementById().

JavaScript getElementById method

     

We can access the specific element of any existing html page by using the method getElementById(). For accessing any element in order to refer to it must have its some unique identity. Therefore we can uniquely identify that specific element in that page.

<input id="txt" type="text" value=""/>

Above line of code creates an input text element and uniquely identifies it with its own identity "id" value which is declared here as id="txt". Each id on the page must be unique. One time if we have marked all of the elements within the HTML page then if we want to access it from JavaScript we can then access them from JavaScript quite easily. 

 

Syntax:

var elementObject = document.getElementById('identity');

Description of Code:

In the following example we have created a web page into which we have defined a text input box and one button when the user clicks on the button it calls the function funcGetElement() which takes the reference to the element and takes the value of it and displays value in the alert message. Here is the full example code for getElementByIdExample.html as follows : 

 <html>
<body>
<script language="JavaScript">
function funcGetElement() {
var elementObject = document.getElementById("txt");
alert(elementObject.value); 

</script>
<div style="background: #ff9900; width:'100%';" align="center">
<font color="#0000ff" size="12pt">
<p>getElementById method</p>
</font>
</div>
<center>
Input text here : &nbsp
<input id="txt" type="text" value=""/><br/>
<input type="button" value="GetElement's Value" onclick="funcGetElement();"/>
</center>
</body>
</html>

Output :

Input your text here to show the use of getElementById() method. Your output would like the following :

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: January 29, 2009

Related Tutorials

Ask Questions?    Discuss: JavaScript getElementById method  

Post your Comment


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