JavaScript DOM Document & Elements
The Document Object Model (DOM) gives JavaScript complete access to all parts of an HTML page. Every web page loaded in a browser becomes a document object, and all HTML elements (like headings, paragraphs, and buttons) become its child elements.
To make your page interactive, you first need to find and access these elements — that’s where DOM element selection methods like getElementById()
, getElementsByClassName()
, and querySelector()
come in.
The document
Object
The document
object represents the entire web page. It’s the root of the HTML DOM tree, and through it, JavaScript can read or modify any element on the page. Think of it as the starting point for all DOM interactions.
Example:
console.log(document.title); // Prints the title of the page
document.title = "New Page Title"; // Changes the page title
Accessing HTML Elements in JavaScript
Accessing HTML elements is one of the most common tasks in JavaScript. The DOM (Document Object Model) provides several methods to find, read, and manipulate HTML elements dynamically — allowing developers to make webpages interactive and responsive.
1. Accessing the Document Structure
Before selecting specific elements, JavaScript allows direct access to key parts of the HTML page:
document.documentElement; // Refers to the <html> element
document.head; // Refers to the <head> element
document.body; // Refers to the <body> element
2. Common Methods to Access Elements
getElementById()
Selects an element by its unique id
attribute.
document.getElementById("main-title");
getElementsByClassName()
Returns an HTMLCollection of elements with the given class name.
document.getElementsByClassName("card");
getElementsByTagName()
Returns an HTMLCollection of elements with the specified tag name.
document.getElementsByTagName("p");
getElementsByName()
Selects all elements with a matching name
attribute.
document.getElementsByName("username");
querySelector()
Returns the first element that matches a CSS selector.
document.querySelector(".btn-primary");
querySelectorAll()
Returns a NodeList of all elements matching a CSS selector.
document.querySelectorAll(".list-item");
3. Accessing Form Elements
JavaScript provides direct access to forms and inputs:
document.forms[0]; // Access the first form
document.forms["loginForm"]; // Access form by name
document.forms[0].elements[0]; // Access specific input field
4. DOM Traversal
Besides direct selection, you can navigate between elements using relationships:
element.parentNode; // Move to parent
element.children; // Access all child elements
element.firstElementChild; // Access the first child
element.nextElementSibling; // Move to next sibling