document.getElementById

getElementById is a function in JavaScript to access the HTML elements. It’s a function of document object and can only access by using document.getElementById.

Example :

<html>
<script>
function sum()
{
var num1 = document.getElementById(‘num1’);
var num2 = document.getElementById(‘num2’);
var res = document.getElementById(‘result’);
res.value = parseInt(num1.value) + parseInt(num2.value);
}
</script>
<body>
Enter First Number : <input type=”text” id=”num1″/> <br/>
Enter Sec. Number : <input type=”text” id=”num2″/> <br/>
Sum : <input type=”text” id=”result”/> <br/>
<input type=”button” onclick=”sum()” id=”res” value=”SUM”/>
</body>
</html>

In the following example sum() is a function defined in javaScript and called onclick event of button, document.getElementById is used to access the html elements and parseInt is used to typecast the string value to integer because when we access textbox value with the help of element.value it always return string value, if we need string values then there is no need to use parseInt.

Leave a Reply