Skip to content

DOM (Document Object Model)

The DOM (Document Object Model) is a tree representation of a page’s HTML content.
With JavaScript, you can select, modify, add, or remove DOM elements to make the page interactive.


There are several ways to select an element on the page:

  • getElementById("id") → select by ID
  • querySelector("selector") → select the first matching element
  • querySelectorAll("selector") → select all matching elements (NodeList)
let title = document.getElementById("title");
let button = document.querySelector("button");
let buttons = document.querySelectorAll("button");

Once an element is selected, you can modify its content and style.

let title = document.getElementById("title");
title.innerText = "New text";
title.style.color = "red";

Differences between innerText, textContent, and innerHTML

Section titled “Differences between innerText, textContent, and innerHTML”
  • innerText → returns only visible text (ignores content hidden via CSS).
  • textContent → returns all text, including hidden.
  • innerHTML → allows inserting HTML (beware of XSS vulnerabilities with external content).

You can create a new element with document.createElement() and insert it into the page.

let newParagraph = document.createElement("p");
newParagraph.innerText = "I am added via JS";
document.body.appendChild(newParagraph);
  • append() → adds to the end (likeappendChild)
  • prepend() → adds to the beginning
  • remove() → removes an element
document.body.prepend(newParagraph); // insert at the beginning
title.remove(); // remove the title element

  • Prefer querySelector and querySelectorAll (more flexible with CSS selectors).
  • Use textContent instead of innerHTML to prevent XSS vulnerabilities.
  • Create and insert elements dynamically instead of modifying raw HTML directly.