JavaScript — The DOM

Vesna Vucinic
2 min readJun 6, 2021

In JavaScript window is global object that has everything (global functions, location, history, XMLHttpRequest , console , localStorage …) and document is a property of the window object.

The document is a global object representing the HTML and content of a webpage. And with JavaScript we can select and change different parts of the webpage by interacting with the document. Understanding how that works requires an understanding of the DOM.

DOM stands for document object model. The DOM is a live entity and changes that JavaScript makes to the DOM alter the webpage. The document represents the DOM of the page.

With document we have methods to get one or more elements from the DOM. They are the following:

· getElementById returns an element with the given ID. This example finds the element with id="space":

let myElement = document.getElementById("space");

· getElementsByClassName to find all HTML elements with the same class name. This example returns a list of all elements with class="item"

letx = document.getElementsByClassName("item");

· getElementsByTagName gets a NodeList by passing in a tag name. This example finds all <p> elements:

let x = document.getElementsByTagName("p");

· querySelector gets the first element that matches one or more CSS selectors. For example if we use the universal selector denoted by * (matches all elements of any type) querySelector() selects the first element in the document:

let firstElement = document.querySelector('*');

· querySelectorAll to find all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc). This example returns a list of all <p> elements with class="item"

let x = document.querySelectorAll("p.item");

And this example finds all elements in the document:

let allElements = document.querySelectorAll('*');

· getElementsByName returns a list of elements by the provided name of the HTML tag.

· getElementsByTagNameNS returns elements with a particular tag name within the provided namespace.

Once we’ve selected an element in the DOM, we can read or affect it. We can replace or change the display of text, for example. Or we can create new nodes and insert them into the DOM.

--

--