Ken Ward's New Java Script Tutorial

Writing with java script

This page explains how we can use java script to write text or even HTML for us. It also explains how to break strings into two or more lines and what to do with marks of elision such as the 'quote' in don't!


The writing above was written by java script itself. To achieve this, all we need to do is to put this code in the place we want java script to write:

<script type="text/javascript">

<!--//

document.write("<h2>Hello</h2>");

//-->

</script>

Not very impressive, but java script actually wrote the stuff at the bottom of this and every page in the tutorial! By writing all the drop-down menus, and working out the next and previous pages,  it saved me a lot of work!


The text in the document.write above is sometimes called a string. The string consists of the HTML heading tags and the 'Hello'. It is enclosed in double quotes (but it could have been enclosed in single quotes).

One thing to remember about java script is that if you do not keep your string to one line, then you will get an error.

My first message was longer than the above, but I could not get a whole string on this page, so, I just had it say 'Hello', which is friendly, isn't it?

You should break up long strings. Another pc or a Mac might wrap the string and give you an error. This is how you write long strings on two or more lines:

document.write("This is java script calling you from "+

"inside your computer.");


exclam.gif (342 bytes)You break the string by adding a quote and a plus sign and begin the next line with another quote. Remember, java script will write this as one line, so allow for a space between the last word of the line and the first one of the next line. If you want to start another line, use \n!


If you use a quote for an abbreviation in a word such as 'don't' then put a backslash in front of it to tell java script that it is a mark of elision and not part of its code. Many errors occur because we forget to do this. For example:

document.write("Don\'t forget to put a "+ "backslash in!");

Broken strings and funny errors which are due to forgetting to put the backslash in words like wouldn't (write wouldn\'t for java script) are major causes of errors! In short, watch your strings and quotes!

If you wish to change the text, etc, of a page after it has been loaded, you might find the following lessons interesting:

Inserting Text

Modifying Existing Text

Deleting Text

Appending Text

Appending Text 2


[If you need to learn more about HTML visit the HTML Tutorial]

I am always pleased to hear from you.
Send your comments to