Home >>Javascript Tutorial >getElementById() method

getElementById() method

document.getElementById() method in JavaScript

The document.getElementById() method in JavaScript returns the element of a specified id. In order to get the value of the input text document. getElementById method is used and the id of the input field needs to be defined.

Let's understand the document.getElementByID method in JavaScript by the following example:

<script type="text/javascript">  
function getcube(){  
var number=document.getElementById("number").value;  
Enter No:<input type="text" id="number" name="number"/><br/>  
<input type="button" value="get the cube" onclick="getcube()"/>  
Output :
Enter No:
A dialogue box where the user will input the value and click on the button named 'get the cube' and a pop-up will appear with the cube of the entered value.

Let's take another Example :

<p>An unordered list:</p>

<p>Click the button to display the innerHTML of the third li element .</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

function myFunction() {
  var x = document.getElementsByTagName("LI");
  document.getElementById("demo").innerHTML = x[2].innerHTML;
Output :

An unordered list:

  • Book
  • Pen
  • Pencil

Click the button to display the innerHTML of the third li element .


No Sidebar ads