#CodeNewbie

#CodingTips

#Frontend

#Fullstack

#JavaScript

#LearnToCode

#Programming

#WebDevelopment

What is the DOM? How JavaScript interacts with HTML

 

Every time you click a button and something changes on a web page, JavaScript is manipulating the DOM. Understanding the DOM is the bridge between writing JavaScript code and making web pages actually do things. This article explains what the DOM is, how to select elements, and how to read and change them.


 

What is the DOM?

DOM stands for Document Object Model. When a browser loads an HTML page, it parses the HTML and creates a tree of objects in memory — one object for every element, attribute, and piece of text. This tree is the DOM.

JavaScript can read and modify this tree at any time, which is what makes web pages dynamic. Adding a new element, changing text, hiding a section, updating a class — all of this happens through the DOM.

/* HTML */
<html>
  <body>
    <h1 id="title">Hello</h1>
    <p class="intro">Welcome</p>
  </body>
</html>

/* DOM tree (simplified) */
document
└── html
    └── body
        ├── h1#title → "Hello"
        └── p.intro → "Welcome"

 

Selecting elements

Before you can do anything with an element, you need to select it. JavaScript gives you several ways to do this.

getElementById()

Selects a single element by its id. Returns the element or null if not found. The fastest selector.

const title = document.getElementById("title");
console.log(title);  →  <h1 id="title">Hello</h1>

querySelector()

Selects the first element that matches a CSS selector. Works with any selector — id, class, tag, attribute.

document.querySelector("#title")          →  h1 element
document.querySelector(".intro")          →  first .intro element
document.querySelector("p")              →  first <p> tag
document.querySelector("input[type=text]") →  first text input

querySelectorAll()

Selects all elements matching a CSS selector. Returns a NodeList (similar to an array).

const allParas = document.querySelectorAll("p");
const allCards = document.querySelectorAll(".card");

allParas.forEach(p => console.log(p.textContent));

// Convert NodeList to array if needed
const arr = [...allParas];
querySelector vs getElementById: Use getElementById when you have an id — it is faster. Use querySelector when you need CSS selector flexibility (classes, attributes, nesting). Use querySelectorAll for multiple elements.

 

Reading and changing content

textContent and innerHTML

const el = document.querySelector("h1");

// Read content
el.textContent   →  "Hello"  ← plain text only
el.innerHTML     →  "Hello"  ← includes HTML tags

// Set content
el.textContent = "Welcome to JS!";
el.innerHTML = "<span>Welcome</span> to JS!";

// innerText respects CSS visibility (hidden text excluded)
el.innerText     →  "Hello"
Never use innerHTML with untrusted user input. It can execute malicious scripts (XSS attacks). Use textContent when you only need to display plain text.

 

Changing styles and classes

Inline styles

const box = document.querySelector(".box");

box.style.color = "red";
box.style.backgroundColor = "yellow";  ← camelCase!
box.style.fontSize = "20px";
box.style.display = "none";            ← hide element

classList — the better way

Instead of setting inline styles directly, it is better practice to toggle CSS classes and let your stylesheet handle the visual changes.

const btn = document.querySelector(".btn");

btn.classList.add("active");      ← add a class
btn.classList.remove("active");   ← remove a class
btn.classList.toggle("active");   ← add if absent, remove if present
btn.classList.contains("active"); →  true or false
btn.classList.replace("old", "new"); ← replace a class

 

Reading and changing attributes

const link = document.querySelector("a");

link.getAttribute("href")          →  "https://example.com"
link.setAttribute("href", "/about");  ← change the href
link.setAttribute("target", "_blank"); ← add new attribute
link.removeAttribute("target");       ← remove it
link.hasAttribute("href")          →  true

// Shorthand for common attributes
link.href    →  "https://example.com"
link.id      →  "my-link"
link.className →  "btn primary"

 

Creating and inserting elements

// 1. Create a new element
const newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph.";
newPara.classList.add("highlight");

// 2. Insert into the DOM
const container = document.querySelector(".container");

container.appendChild(newPara);     ← add at the end
container.prepend(newPara);         ← add at the start
container.insertBefore(newPara, ref);← before a reference element

// 3. Remove an element
newPara.remove();                   ← removes itself from DOM

Traversing the DOM

Once you have an element, you can navigate to its relatives — parent, children, and siblings.

const el = document.querySelector(".item");

el.parentElement       ← parent node
el.children            ← all child elements (HTMLCollection)
el.firstElementChild   ← first child element
el.lastElementChild    ← last child element
el.nextElementSibling  ← next sibling
el.previousElementSibling ← previous sibling

 

Practical example — toggle a menu

Here is a real pattern you will use constantly — toggling a mobile menu open and closed using classList.

/* HTML */
<button id="menuBtn">Menu</button>
<nav id="nav" class="nav">...</nav>

/* CSS */
.nav { display: none; }
.nav.open { display: block; }

/* JavaScript */
const btn = document.getElementById("menuBtn");
const nav = document.getElementById("nav");

btn.addEventListener("click", () => {
  nav.classList.toggle("open");
});
This pattern — select → listen → toggle class — is the foundation of almost every interactive UI component: dropdowns, modals, tabs, accordions. Master this and you understand 80% of DOM manipulation.

 

Key takeaways

The DOM is the browser's in-memory tree representation of your HTML — JavaScript can read and modify it at any time. Use getElementById for id-based selection and querySelector / querySelectorAll for CSS selector-based selection. Use textContent to read and write plain text safely — avoid innerHTML with user input. Prefer classList.toggle() over setting inline styles directly. Use createElement and appendChild to dynamically add elements. The core pattern of DOM interaction is: select an element → listen for an event → update the DOM.