DOM (Document Object Model)
What is the DOM?
Section titled “What is the DOM?”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.
Selecting elements
Section titled “Selecting elements”There are several ways to select an element on the page:
getElementById("id")
→ select by IDquerySelector("selector")
→ select the first matching elementquerySelectorAll("selector")
→ select all matching elements (NodeList)
let title = document.getElementById("title");let button = document.querySelector("button");let buttons = document.querySelectorAll("button");
Modifying content and style
Section titled “Modifying content and style”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).
Creating and inserting an element
Section titled “Creating and inserting an element”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);
Other useful methods
Section titled “Other useful methods”append()
→ adds to the end (likeappendChild
)prepend()
→ adds to the beginningremove()
→ removes an element
document.body.prepend(newParagraph); // insert at the beginningtitle.remove(); // remove the title element
Best practices
Section titled “Best practices”- Prefer
querySelector
andquerySelectorAll
(more flexible with CSS selectors). - Use
textContent
instead ofinnerHTML
to prevent XSS vulnerabilities. - Create and insert elements dynamically instead of modifying raw HTML directly.