JS Basics: How to get an HTML element by its ID in JavaScript

Hey all, I think I’m now comfortable enough to start writing about the basics of JavaScript. Though I will assume you know how to add JavaScript to a HTML page.

So here we are, the most handy thing of all: how to get a reference to an HTML element by the ID number.

document.getElementById('myElement');

This will find the HTML element with the ID of “myElement” .

here is some example HTML:

<html>
<head>
</head>
<script type="text/javascript">
<!--
function run()
{
	alert(document.getElementById('myDiv'));
}
-->
</script>
<body onload="run()">
<div id="myDiv"></div>
</body>
</html>

Stay Cool!

-Bill

Tags: , , ,

Author:Alan Hamlyn

-- Alan Hamlyn Founder of Wuup
  • http://www.wuup.co.uk Alan Hamlyn

    We will all indeed ‘stay cool’ :)

  • http://www.bigtallbill.co.uk Bill Nunney

    See that you do!