How to Accessing HTML Elements using javascript?


How to Accessing HTML Elements using javascript?

✍: Guest


To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example below:

<form action="">
<input type="button" id="useless" name="mybutton" value="doNothing" />

We can use the "getElementById" method using the "id" attribute to identify the element (which is generally preferred)

document.getElementById("useless").style.color = "red";

or we can use the "name" attribute to identify the element:

document.forms[0] = "blue";

Here is another example of accessing elements with the DOM object:

<script type="text/javascript" >
function showStatus() {
var selectWidget = document.forms.beerForm.elements["beer"];
var myValue = selectWidget.options[selectWidget.selectedIndex].value;
alert('You drank a \"'+ myValue +"\"");
return true;

<form name="beerForm" action="">
<select name="beer">
<option selected="selected">Select Beer</option>
<option>Amstel Light</option>
<option>Corona Light</option>

<input type="button" name="submitbutton" value="Drink"
onclick="showStatus()" />

2008-09-23, 4621👍, 0💬