Categories

Dec 4, 2019 in JavaScript
Q: How To Accessing Elements Using Javascript?

1 Answer

Dec 4, 2019

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

<body>

<form action="">

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

</form>

</body>

We can use the "getElementById" method (which is generally preferred)

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

or we can use the older hierarchical navigation method,

document.forms[0].mybutton.style.color = "blue";

Notice that this uses the "name" attribute of the element to locate it.

# Example of Accessing Elements in a DOM.

<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;

}

</script>

<form name="beerForm" action="">

<select name="beer">

<option selected="selected">Select Beer</option>

<option>Heineken</option>

<option>Amstel Light</option>

<option>Corona</option>

<option>Corona Light</option>

<option>Tecate</option>

</select>

<input type="button" name="submitbutton" value="Drink"

onclick="showStatus()" />

</form>

Click here to read more about JavaScript
Click here to read more about Insurance

Related questions

Madanswer
Dec 4, 2019 in JavaScript
Dec 4, 2019 in JavaScript
Jul 16, 2019 in JavaScript
...