JavaScript and HTML

JavaScript and the web go together like cheese and pizza: You could have one without the other, but why?

JavaScript gives web pages the ability to change dynamically in response to user input. To get the most out of the integration between JavaScript and the web, you need to know a little bit about how web pages are built.

In this Tutorial, we explore the language of the web, HTML, and we show you how to use JavaScript to work with and change the HTML inside of web pages.

We love javscript

Writing HTML

HTML stands for Hypertext Markup Language. That’s a fancy way of saying that HTML is a language that’s used to create links (hypertext). HTML is so much more than simply a language for creating links, though.

HTML forms the skeleton that the text, pictures, and JavaScript in web pages attaches to.

Seeing what text looks like without HTML

Markup languages, such as HTML, were invented in order to give documents (such as letters, books, or essays) structure that a computer can understand and do things with.

Listing 5-1 shows a simple list that a person can understand with no problem.

A List
Things I Need
Listing 5-1: A List

As a person, you see this list and immediately understand it. But to a computer, this list has some issues. For example, a computer has no way of knowing that Things I Need is a title rather than an item on the list. Figure 5-1 is what it looks like when you view Listing 5-1 with a web browser.

To make this text document understandable to a web browser, we need to use HTML to “mark it up.”

Using HTML: It’s all about the tags

HTML is made up of tags. The tags on clothes give you information about what the clothes are made of and how to wash them. Similarly, tags in HTML give you information about the content of a web page.

Listing 5-1 rendered as HTML in JSFiddle
Figure 5-1: Listing 5-1 rendered as HTML in JSFiddle.

Tags are made up of keywords inside of angle brackets (< and >) and then come in two basic types: the beginning tag and the ending tag. Here’s an example of a beginning tag:


The p tag, is how you mark up text in a document as a paragraph.

Most beginning tags also have matching ending tags. The only difference between a beginning tag and an ending tag is that an ending tag has a / before the name of the tag. For example, here’s the ending p tag:


To use tags, just put the thing that you want to mark up (such as text, images, or even other tags) between the beginning and ending tags. For example, here’s how you would mark up a paragraph of text in HTML.

<p>This is a paragraph of text. A paragraph has space before and after it in order to separate it from the other paragraphs of text in a document.</p>

When you have a beginning tag, an ending tag, and content between them, we call the whole thing an HTML element.

HTML has a bunch of tags that you can use to label different parts of a document. Examples of tags include <p> for paragraph, <img> for image, <audio> for audio clips, <video> for video clips, <header> for the top of a web page, and <footer> for the bottom of a web page.

Listing 5-2 shows the list from Listing 5-1 marked up as an HTML document, made up of tags and text.

       <title>My Grocery List</title>
       <h1>Things I Need</h1>
Listing 5-2: A Simple HTML Document.

Figure 5-2 shows what the web page in Listing 5-2 looks like when you view it with a web browser. That’s much better, right?

Listing 5-1 rendered as HTML in JSFiddle
Figure 5-2: Listing 5-2 rendered as HTML in JSFiddle.

Notice that HTML tags don’t actually appear in the web browser. Instead, they modify how the web browser displays text, images, and more.

Looking at the basic structure of a web page

Creating web pages is pretty easy once you know a few things about how they’re built. The first thing to know is that most web pages share a very similar basic structure, and they all must abide by just a few basic rules.

The first rule of creating HTML documents is that tags need to be opened and closed in the right order. One way to remember the order in which tags are opened and closed is FILO, which stands for First In, Last Out.

Notice that the web page in Listing 5-2 starts with the <html> tag and ends with the </html> tag. This is how every web page should start and end. All the other tags in a web page are “inside” the html tags, and they’re closed according to FILO.

For example, the <head> element is inside of <html>. Therefore, the closing head tag must come before the closing html tag. The <ol> tag (which stands for ordered list) comes after the <body> tag, so <ol> is inside of <body> and the </ol> tag must come before the </body> tag.

Another rule of creating HTML documents is that web pages always have a head element and a body element.

  • The head element: The head element is like the brain of your web pages. JavaScript code often goes into the head element, but it doesn’t display in the web browser window.

    In Listing 5-2, we have only a title element in the head. The title is what displays at the top of the browser window or in your browser’s tab when you’re on a web page. The contents of the title element are also typically what shows up as a link in search results.

  • The body element: The body element is where everything that you want to display in the web browser goes.

    In Listing 5-2, we have several elements in the body. Let’s take a look at each of these:

    • The h1 element: The h1 element can be used to identify the most important header on your web pages. Headers typically identify sections of documents or web pages. For example, if this Tutorial were a web page, the first h1 element would come right after the Tutorial introduction and would read “Writing HTML.”
    • The ol element: Following the h1 element, we have an ol element. ol stands for ordered list. An ordered list is a list of items that are numbered or lettered in a particular order. HTML also lets you make unordered lists, by using the ul (for unordered list) tag.
    • The li element: Following the ol element, we have an li element. Inside of either an ol or ul element, you can use any number of li elements (li stands for list item) to create the individual list items in your list.

Creating your first web page

Follow these steps to make your own list in JSFiddle.

  • Open your web browser and browse to
  • Drag and drop the pane borders to make the HTML pane in JSFiddle as large as you like.
  • We’re only going to be working with the HTML pane for now, so make sure you’re comfortable and have plenty of space.
  • Type the following basic HTML template into the HTML pane.
              <title>HTML Template</title>
              <h1>A basic HTML template</h1>
      As soon as you type <html>, you get a warning message from JSFiddle, as shown in Figure 5-3, telling you that <html> is already included in the output. What’s going on here is that the basic HTML template is so basic that JSFiddle will just help you out by putting it in there for you. Thanks, JSFiddle!
      JSFiddle warning
      Figure 5-3: JSFiddle shows a warning.
  • Because the basic template is already there, go ahead and delete everything from the HTML window except for what’s between <body> and </body> (the h1 element).
  • Always keep in mind that the <html>, <head>, and <body> elements should be part of every web page, even if you don’t need to type them yourself when you’re working in JSFiddle.

  • Click Run.
    1. The text between the <h1> and </h1> tags will display in the Output pane, formatted as a first‐level heading, as shown in Figure 5-4.
      A basic html template
      Figure 5-4: Running a basic HTML template in JSFiddle.

Knowing Your HTML Elements

HTML has quite a few elements. Because this is a JavaScript tutorial, we don’t have room to talk about each of the elements here. But we’ll cover just enough of them to allow you to build some awesome web pages. For the rest, you can go online to read more.

There are some really good books on HTML, such as Beginning HTML5 and CSS3 For Dummies, by Ed Tittel and Chris Minnick (Wiley). You can also find a complete list of every HTML element online. Our favorite free online resource is at mozilla documents.

Table 5-2 lists the most commonly used HTML elements, along with descriptions of what they’re for.

Table 5-2 The Most Common HTML Elements
Element Name Description
<h1> through <h6>Headings (levels 1 through 6)A section heading.
<p>ParagraphA paragraph.
<em>EmphasisAdds emphasis to a word or words. Typically displayed as italics in web browsers.
<strong>StrongRepresents strong importance. Typically displayed as bold text in web browsers.
<a>AnchorA link.
<ul>Unordered listA bulleted list.
<ol>Ordered listOrdered list
<li>List itemAn item within an ordered or unordered list.
<img>ImageAn image.
<hr>Horizontal ruleA horizontal line on the page.
<div>DivisionA way to separate a document into different parts.
Listing 5-2: HTML elements

Let’s have some fun with your new elements. We’re going to write a fun web page all about you!

Go back to JSFiddle and follow these steps:

  • Delete everything from the HTML pane and click Run. The Output pane should now be blank.
  • Create a first‐level header for your page, using the h1 element, and put your name into it.
  • Put a horizontal rule below the first‐level header.
  • Add a p element and type a favorite quote, a sentence about yourself, or the following text between the start and end tags: "I'm learning to build dynamic web pages with JavaScript and HTML!"
  • Put the em element around the sentence (inside of the p element) you typed in the previous step.
  • Click Run.
      If you’re following along closely, your code should look something like this:
                  <p><em> I'm learning to build dynamic web pages with JavaScript 
                  and HTML!</em></p>
      The output should now look something like Figure 5-5 (but with your own information, of course!).
      home page html
      Figure 5-5: The beginnings of a beautiful home page.
  • Create another horizontal rule, followed by a new paragraph.
  • Create a level‐2 heading (using the h2 element) and put the words “Things I Like” inside of it.
  • Create a new paragraph and put the following text into it:"Here are some of the things I like to do:"
  • Now, create an unordered list with three blank list items. Here’s the code for that:
  • Put something that you like to do into each of the list item elements.
      Listing 5-3 shows what our sample code looks like now.
                  <p><em>I'm learning to build dynamic web pages with JavaScript 
                      and HTML!</em></p>
                  <h2>Things I Like</h2>
                  <p>Here are some of the things I like to do:</p>
      Listing 5-3: The Updated Home Page
      Click Run to preview your web page in the output pane. It should now look like Figure 5-6.
      The home page, with a list of things.
      Figure 5-6: The home page, with a list of things.

Adding Attributes to Elements

HTML elements are pretty powerful just by themselves, and they can make web browsers do some pretty fancy things with your content. However, HTML has another trick up its sleeve that makes HTML even better: HTML attributes!

HTML attributes are a way to give web browsers more information about elements. Attributes are added to elements using what’s called a name/value pair. For example, the img element uses attributes to tell what image should be displayed, and what should be displayed instead of the image if the file isn’t found:

<img src="picture.jpg" alt="Here's a picture of me">

In this example, src and alt are attributes.

Each element in HTML has a list of attributes that can be added to it. Some attributes, such as src and alt, change the way an element behaves or what it does. Other attributes, such as the id attribute, just provide the browser with more information about the element.

The id attribute uniquely identifies a single element in your document. You may have any number of li elements, for example, but if you give each li element an id attribute, you can tell them all apart . . . and so can JavaScript!

We’ll be making use of the id attribute quite a bit in upcoming programs.

Let’s add some id attributes to the HTML in your home page now.

  • Add an id attribute to the h1 to identify it as containing your name.<h1 id="myName">
  • Find the p element between the two hr elements, and modify the starting tag to add an id of aboutMe, like this: <p id="aboutMe">
  • Add a unique id attribute to each of the list items, like this:
      <li id="firstThing"></li>
      <li id="secondThing"></li>
      <li id="thirdThing"></li>

When you’re finished adding id attributes, your web page should look something like Listing 5-4.

<h1 id="myName">SirNode</h1>
        <p id="aboutMe"><em>I'm learning to build dynamic web 
                pages with JavaScript and HTML!</em></p>
        <h2>Things I Like</h2>
        <p>Here are some of the things I like to do:</p>
           <li id="firstThing">Write</li>
           <li id="secondThing">Dance</li>
           <li id="thirdThing">Travel</li>
Listing 5-4: The Updated Home Page with id Attributes Added

Click Run to preview the web page in JSFiddle. You should notice . . . nothing. The page looks exactly the same with the id attributes as it does without them. Yes, we know, it’s not that exciting. But wait until you see what JavaScript can do with id attributes!

Changing HTML with JavaScript

By using JavaScript, you can change any part of an HTML document in response to input from the person browsing the page. We show you exactly how to do that in this section.

But before we get started, let’s take a look at a couple concepts that we use in this section. The first is a method called getElementById.

As discussed in Tutorial 3, a method is an action that’s done to or by an object in a JavaScript program.

Fetching elements with getElementById

getElementById is probably the easiest and most commonly used way for JavaScript programmers to work directly with HTML. Its purpose is to locate an individual element in a document so that you can change it, delete it, or add something to it.

Another word for locating an element is selecting an element.

To use getElementById, first make sure that the element you want to select has an id attribute. Then just use the following formula to locate that element:


For example, to select an element with an id value of myName, you can use this code:


Getting what’s inside an element with innerHTML

When you have an element, the next logical thing to do is to make a change to it.

innerHTML is a property of every element. It tells you what’s between the starting and ending tags of the element, and it also lets you set the contents of the element.

A property describes an aspect of an object. It’s something that an object has as opposed to something that an object does.

For example, let’s say you have an element like the following:

<p id="myParagraph">This is <em>my</em> paragraph.</p>

You can select the paragraph and then change the value of its innerHTML with the following command:

document.getElementById("myParagraph").innerHTML = "This 
    is <em>your</em> paragraph!";

Trying it out: Changing a list

Now that you know a little about getElementById and innerHTML, let’s take a look again at our HTML home page.

You’ll add a button and JavaScript code to your home page to let you change your list of favorite things with the click of a button.

  • Add a button below the list with the following HTML:
      <button id="changeList" type="button">
                  Change Your List
      The button element causes the browser to create a button in your browser window with the label of the button set to the text between the starting and ending tags.
  • Create three new variables in the JavaScript pane.
      var item1;
      var item2;
      var item3;
      These three variables will be used to hold the values input by the user before they get written to the web page.
  • Make JavaScript pay attention to clicks on the button by adding this to the JavaScript pane in JSFiddle:
      document.getElementById("changeList").onclick = newList;
      We use a method called getElementById to locate the element in the document that has an id attribute set to changeList. As you know, this is the id value of the button.
      When JavaScript has found the button, we use the onclick event handler to tell it to watch for clicks on that button. An event handler is exactly what it sounds like. It tells JavaScript how to handle different types of events that happen in the browser. In this case, mouse clicks.
      If the event handler detects a click on the button, we tell it to run the function that we’ve called newList. A function is like a program within a program. We talk much more about functions in Tutorial 12. For now, all you need to know is that functions don’t run until you tell them to by “calling” them.
  • Type these lines to ask the user for new list items:
      function newList(){
          item1 = prompt("Enter a new first thing: ");
          item2 = prompt("Enter a new second thing: ");
          item3 = prompt("Enter a new third thing: ");
      The first line of this block of code is what makes it a function. It tells JavaScript not to run the code between { and } until the function is called (using its name, newList).
      Inside the function, we gather three new list items from the user, using the prompt command.
      Finally, we tell JavaScript to run the function called updateList, which we’ll write in the next step.
  • Tell JavaScript to update the three list items.
      function updateList() {
          document.getElementById("firstThing").innerHTML = item1;
          document.getElementById("secondThing").innerHTML = item2;
          document.getElementById("thirdThing").innerHTML = item3;
      The updateList function finds each of the list items using their id attribute values. It then uses a method called innerHTML to change the value that’s between the starting and ending tags of the list item to the values that the user entered into the prompt.
      After the updateList function gets run, the values of the three list items should change to the new values entered by the user.
      When you’re finished, your code in the JavaScript pane should match Listing 5-5. Check it very carefully before moving on to make sure you don’t have any syntax errors.
      var item1;
      var item2;
      var item3;
      document.getElementById("changeList").onclick = newList;
      function newList() {
          item1 = prompt("Enter a new first thing: ");
          item2 = prompt("Enter a new second thing: ");
          item3 = prompt("Enter a new third thing: ");
      function updateList() {
          document.getElementById("firstThing").innerHTML = 
          document.getElementById("secondThing").innerHTML = 
          document.getElementById("thirdThing").innerHTML = 
      Listing 5-5: The Final JavaScript for the HTML Homepage App
  • Click Run to try out your new program.

If you did everything correctly, you should now be able to click the button, enter new text into each of the three prompt windows, and then see the new items instead of the three original list items, as shown in Figure 5-7.

JSFiddle warning
Figure 5-7: The final, changeable, list program.