How to Access HTML Form Elements in JavaScript

By John Paul Mueller

As with any other HTML elements, you can interact directly with HTML5 elements in JavaScript. The trick is to ensure that the elements you choose will work with the browsers and platforms you need to support.

In this example, you see how to use the <figure> and <figcaption> tags as part of a solution that loads an image from disk and stores it in an <img> tag. The following code shows the HTML you use to perform the task.

<figure onclick="Clicked()">
  <img id="Image"
  <figcaption id="Caption" />

The <figure> tag acts as a container that holds the <img> and <figcaption> tags. The use of a container like this means that you can perform tasks such as formatting both image and caption at the same time.

Events are also handled jointly. In this case, it doesn’t matter whether the user clicks the image or the caption, the application calls Clicked(). In this case, all that Clicked() does is display a message to the user as shown here:

function Clicked()
  // Display a message.
  alert("You clicked the image.");

JavaScript is fully capable of accessing these elements. In this case, the <img> tag is empty when the form loads. Clicking a button displays the image onscreen by changing the <img> tag content. Here’s the code needed to load the image:

function LoadImage()
  // Specify the image.
  var Image = document.getElementById("Image");
  Image.alt = "This is a test image.";
  Image.src = "TestImage.png";
  // Set the caption.
  var Caption = document.getElementById("Caption");
  Caption.innerHTML = "A Test Image";

When working with the <img> tag, you access the src (image source) and alt (image alternative text description) attributes directly. Set the <figcaption> content using the innerHTML property.