JavaScript HTML DOM

When a browser loads a page, it builds a tree of objects from the HTML. This tree is the DOM (Document Object Model). JavaScript uses the DOM to read and change the page.

<body>
  <h1 id="title">Hello</h1>
  <p class="note">First note</p>
  <p class="note">Second note</p>
</body>

Select elements

MethodReturns
document.getElementById("id")One element with that id
document.querySelector("css")The first element that matches a CSS selector
document.querySelectorAll("css")All matching elements (a list)
document.getElementsByClassName("c")All elements with a class
const title = document.getElementById("title");
const firstNote = document.querySelector(".note");
const allNotes = document.querySelectorAll(".note");

console.log(title.textContent);
console.log(firstNote.textContent);
console.log(allNotes.length);
Output of the above program is

Hello
First note
2


Change text and HTML

title.textContent = "Welcome";
firstNote.innerHTML = "<strong>Important</strong> note";
The page after the code runs

Welcome

Important note

Second note


Change attributes and style

const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href"));

title.style.color = "tomato";
title.style.fontSize = "32px";

For many style changes it is cleaner to switch a CSS class on and off:

title.classList.add("highlight");
title.classList.remove("highlight");
title.classList.toggle("highlight");
console.log(title.classList.contains("highlight"));
Output of the above program is

true

Note: The script must run after the HTML elements exist. Put the <script> at the end of the body, or use defer. querySelectorAll() returns a NodeList, which you can loop with forEach or for...of.

Summary

  • The DOM is the tree of the page that JavaScript can read and change.
  • Select with getElementById, querySelector and querySelectorAll.
  • Change text with textContent, style with style or classList.
  • Next: DOM Manipulation.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.