JavaScript ยท Chapter 52 of 55

JavaScript DOM Manipulation

The DOM (Document Object Model) represents the HTML page as a tree of objects that JavaScript can read and modify, letting you dynamically change content, styles, and structure.

Common methods include `document.getElementById()`, `document.querySelector()` to find elements, and properties like `.innerHTML`, `.textContent`, and `.style` to change them.

Selecting elements

`document.getElementById('id')` finds one element by ID. `document.querySelector('.class')` uses CSS selector syntax and is more flexible.

Modifying elements

`.textContent` sets plain text, `.innerHTML` sets HTML markup, and `.style.property` changes CSS directly from JavaScript.

Example 1 (javascript)
let el = document.querySelector("#title");
el.textContent = "Updated!";

Selects an element by ID and changes its text content.

Example 2 (javascript)
let box = document.querySelector(".box");
box.style.backgroundColor = "blue";

Directly modifies an inline CSS style via JavaScript.

Key points

  • The DOM represents HTML as a tree of manipulable objects.
  • querySelector()/querySelectorAll() use CSS selector syntax to find elements.
  • textContent sets plain text; innerHTML sets HTML markup.
  • .style.property changes inline CSS from JavaScript.
๐Ÿ’ก Note: Prefer textContent over innerHTML when inserting user-provided text, to avoid XSS security risks.

๐Ÿ“ Quick Quiz

1. What does the DOM represent?

2. Which selects elements using CSS selector syntax?

3. Which is safer for inserting user text?