Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

DOM Elements

This page shows you how to locate and access HTML elements within an HTML page.

Finding HTML Elements

In JavaScript, you often need to manipulate HTML elements, and to do so, you must first locate them. There are several methods for finding HTML elements:

  • By id
  • By tag name
  • By class name
  • By CSS selectors
  • By HTML object collections

Finding HTML Element by Id

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

This example finds the element with id=”intro”:

Example

const element = document.getElementById(“intro”);

If the element is found, the method will return the element as an object (assigned to element).

If the element is not found, element will be set to null.

Finding HTML Elements by Tag Name

This example locates all <p> elements:

Example

const element = document.getElementsByTagName(“p”);

This example locates the element with id=”main”, and then retrieves all <p> elements within it.

Example

const x = document.getElementById(“main”);
const y = x.getElementsByTagName(“p”);

Finding HTML Elements by Class Name

To find all HTML elements with the same class name, use getElementsByClassName().

This example returns a list of all elements with class=”intro”.

Example

const x = document.getElementsByClassName(“intro”);

Finding HTML Elements by CSS Selectors

To find all HTML elements that match a specific CSS selector (such as id, class names, types, attributes, or attribute values), use the querySelectorAll() method.

This example returns a list of all <p> elements with class=”intro”.

Example

const x = document.querySelectorAll(“p.intro”);

Finding HTML Elements by HTML Object Collections

This example locates the form element with id=”frm1″ in the forms collection and displays the values of all its elements.

Example

const x = document.forms[“frm1”];
let text = “”;
for (let i = 0; i < x.length; i++) {
  text += x.elements[i].value + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;

The following HTML objects (and object collections) are also accessible:

  • document.anchors
  • document.body
  • document.documentElement
  • document.embeds
  • document.forms
  • document.head
  • document.images
  • document.links
  • document.scripts
  • document.title