A+ A-

Javascript code for The getElementById method

The getElementById method is the most powerful and the most complex (but don't worry, it's really easy!). Everything on a web page resides in a box. A paragraph (<P>) is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them.

[code type="HTML"]<html>
<head>
</head>
<body>
<div id="feedback">
</div>
<script type="text/javascript">
document.getElementById('feedback').innerHTML='Hello World!';
</script>
</body>
</html>[/code]

The page is a little bigger now but it's a lot more powerful and scalable than the other two. Here we defined a division <div> and named it "feedback". That HTML has a name now, it is unique and that means we can use Javascript to find that block, and modify it. We do exactly this in the script below the division! The left part of the statement says on this web page (document) find a block we've named "feedback" ( getElementById('feedback') ), and change its HTML (innerHTML) to be 'Hello World!'. We can change the contents of 'feedback' at any time, even after the page has finished loading (which document.writeln can't do), and without annoying the user with a bunch of pop-up alert boxes (which alert can't do!). It should be mentioned that innerHTML is not a published standard. The standards provide ways to do exactly what we did in our example above. That mentioned, innerHTML is supported by every major Browser and in addition innerHTML works faster, and is easier to use and maintain. It's, therefore, not surprising that the vast majority of web pages use innerHTML over the official standards. While we used "Hello World!" as our first example, its important to note that, with the exception of <script> and <style>, you can use full-blown HTML. Which means instead of just Hello World we could do something like this…

[code type="JavaScript"]
<html>
<head>
</head>
<body>
<div id='feedback'>
</div>
<script type='text/javascript'>
document.getElementById('feedback').innerHTML='<P>
<font color=red>Hello World!</font>';
</script>
</body>
</html>[/code]

In this example, innerHTML will process your string and basically redraw the web page with the new content. This is a VERY powerful and easy to use concept. It means you can basically take an empty HTML element (which our feedback division is) and suddenly expand it out with as much HTML content as you'd like.

The getElementById method is the most powerful and the most complex (but don't worry, it's really easy!). Everything on a web page resides in a box. A paragraph (

) is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them.