1. Computing

JavaScript By Example

1. First JavaScript

By

In this tutorial series we are going to look at a large number of examples of JavaScript code. Each of the scripts is intended to introduce you to a particular JavaScript statement and demonstrate how it works.

Since best practice is to put the HTML, CSS, and JavaScript into separate files, the examples will show each separately. The code in the HTML that links the files together will assume that any CSS to link to the HTML for example 99 will be called example99.css and the JavaScript for that example will be called example99.js and so you will be able to test each script for yourself if you copy the code into separate files using those filenames.

We'll begin with a first example that demonstrates how we attach JavaScript into a web page so that it can interact with the page. Since just about all programming languages use a program that displays "hello world" as its first example we'll start with an example that dynamically adds that into the web page.

Note that the script tag is located immediately prior to the closing body tag as this is the most effective and efficient place to attach JavaScript to a web page. We'll look in more detail at what the JavaScript in this example actually does in a later tutorial.

HTML


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 01</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example01.js"></script>
</body>
</html>

JavaScript


document.getElementById('ex').innerHTML = 'hello world';

©2014 About.com. All rights reserved.