Clean β’ Professional
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.
document ObjectThe 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 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.
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
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");
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
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Β