JavaScript HTML DOM Elements


This page shows you how to locate and use HTML elements on a webpage.


Finding HTML Elements

Frequently, when using JavaScript, you may need to control HTML elements.

To achieve this, you need to locate the elements initially. There are various methods to accomplish this:

  • Finding HTML elements by id.
  • Finding HTML elements by tag name.
  • Finding HTML elements by class name.
  • Finding HTML elements by CSS selectors.
  • Finding HTML elements by HTML object collections.

Finding HTML Element by Id

The simplest method to locate an HTML element in the DOM is by using its element id.

This example locates the element with the id="intro":

If the element is located, the method will give back the element as an object (in element).

If the item is not located, the 'element' will hold the value null.


Finding HTML Elements by Tag Name

This example identifies all <p> elements.

This example locates the element identified by the id="main". Afterward, it identifies all

elements within the "main" element.


Finding HTML Elements by Class Name

To locate all HTML elements sharing the same class name, employ the getElementsByClassName() method.

This example provides a list of elements having the class class="intro".


Finding HTML Elements by CSS Selectors

To locate all HTML elements that correspond to a particular CSS selector (such as id, class names, types, attributes, attribute values, etc.), you can employ the querySelectorAll() method.

This example provides a list of all <p> elements that have the class="intro".


Finding HTML Elements by HTML Object Collections

This example locates the form with the id="frm1"in the collection of forms. It then shows the values of all the elements in that form.

These HTML elements (and groups of elements) can also be reached: