Dom

Learn how to interact with and modify HTML elements using JavaScript — bring your webpages to life with dynamic content, styles, and interactivity.

Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:

The Document Object Model (DOM) is a programming interface for web documents. It represents your HTML page as a tree of objects that JavaScript can interact with.

Think of the DOM as a live representation of your webpage that you can read and modify in real-time.

Imagine your HTML is like a blueprint of a house. The DOM is the actual house that's been built from that blueprint. With JavaScript, you can walk through that house, change the paint colors, move furniture around, or even add new rooms — all while people are inside!

Everything on a webpage — every paragraph, image, button, and div — is represented as an object in the DOM tree.

Without the DOM, web pages would be static and boring. DOM manipulation is what makes the web interactive :

Before you can manipulate an element, you need to select it. JavaScript gives you several powerful methods to find elements in the DOM.

📌 Method 1: getElementById

The most direct way to select an element — by its unique id attribute.

📌 Method 2: getElementsByClassName

Select all elements with a specific class name. Returns an HTMLCollection (array-like object).

📌 Method 3: querySelector (Modern & Recommended)

The most versatile method — uses CSS selectors to find elements. Returns the first match .

📌 Method 4: querySelectorAll

Like querySelector , but returns all matching elements as a NodeList.

Use querySelector and querySelectorAll for modern projects. They're more flexible and work just like CSS selectors you already know!

Once you've selected an element, you can change what's inside it.

🔤 Using textContent (Safer)

Changes the plain text inside an element. HTML tags are treated as text, not rendered.

🏗️ Using innerHTML (More Powerful)

Changes the HTML content inside an element. Tags are parsed and rendered.

Be careful with innerHTML when inserting user-provided content! It can expose your site to XSS (Cross-Site Scripting) attacks. Use textContent for user input, or sanitize the HTML first.

📝 Example: Updating a Counter

You can modify CSS styles directly using JavaScript's style property.

🖌️ Basic Styling

🎭 Multiple Styles at Once

🔄 Example: Theme Switcher

For complex styling, it's better to add/remove CSS classes rather than inline styles. This keeps your styling logic in CSS where it belongs!

The classList API is the modern, clean way to manage CSS classes on elements.

➕ Adding Classes

➖ Removing Classes

🔄 Toggling Classes

The most useful method — adds the class if it's not there, removes it if it is.

✅ Checking if a Class Exists

📝 Real-World Example: Tabs

JavaScript lets you create brand new HTML elements and insert them into your page dynamically.

🆕 Creating Elements

📦 Inserting Elements — Different Ways

🗑️ Removing Elements

📋 Example: To-Do List

Attributes are the properties you set in HTML tags, like id , src , href , data-* , etc.

🎯 Getting Attributes

✏️ Setting Attributes

🗑️ Removing Attributes

📊 Data Attributes (data-*)

Custom attributes that start with data- are perfect for storing extra information.

Try out DOM manipulation in this live editor. The code demonstrates selecting, creating, and modifying elements.

Test your DOM manipulation skills with these challenges:

Create a function that generates a user profile card with:

Build a mini shopping cart that lets users add items, increase quantity, remove items, and see the total price update in real-time — all using DOM manipulation!

💬 Recap

DOM manipulation is the bridge between your data and what users see. Master it, and you can build anything — from simple counters to complex web applications!

Next up: Learn how to respond to user actions with Event Handling ! 🎉

You can now select, modify, create, and remove HTML elements using JavaScript — making your webpages truly dynamic!

Up next: JavaScript Events — respond to clicks, keyboard presses, and more! ⚡

Practice quiz

What does the DOM represent?

  • A CSS stylesheet
  • A database of users
  • Your HTML page as a tree of objects JavaScript can interact with
  • The browser's network requests

Answer: Your HTML page as a tree of objects JavaScript can interact with. The Document Object Model represents the page as a live tree of objects you can read and modify.

What does document.querySelector('.box') return?

  • The first element matching the CSS selector
  • All elements with class box
  • An array of nodes
  • The element's text

Answer: The first element matching the CSS selector. querySelector returns the first match for a CSS selector, or null if none is found.

Which method returns ALL matching elements as a NodeList?

  • getElementById
  • querySelector
  • getElementByClass
  • querySelectorAll

Answer: querySelectorAll. querySelectorAll returns every matching element as a NodeList.

Why is textContent safer than innerHTML for user input?

  • It is faster
  • It treats input as plain text, preventing XSS
  • It renders HTML tags
  • It validates emails

Answer: It treats input as plain text, preventing XSS. textContent escapes HTML so injected script tags display as text rather than executing — preventing XSS.

What does element.classList.toggle('open') do?

  • Adds the class if absent, removes it if present
  • Always adds the class
  • Always removes the class
  • Renames the class

Answer: Adds the class if absent, removes it if present. toggle adds the class when it is missing and removes it when present.

How do you create a new element in the DOM?

  • document.newElement('div')
  • document.addElement('div')
  • document.createElement('div')
  • new Element('div')

Answer: document.createElement('div'). document.createElement('div') creates a new, detached element you then insert into the page.

Which appends a node as the last child of a parent?

  • parent.insertBefore(node)
  • parent.appendChild(node)
  • parent.prepend(node, null)
  • parent.remove(node)

Answer: parent.appendChild(node). appendChild adds the node as the last child of the parent element.

What is the modern way to remove an element from the DOM?

  • element.delete()
  • element.destroy()
  • element.hide()
  • element.remove()

Answer: element.remove(). element.remove() removes the element itself; the older way is element.parentNode.removeChild(element).

How is the CSS property background-color written in element.style?

  • background-color
  • backgroundColor
  • background_color
  • BackgroundColor

Answer: backgroundColor. Hyphenated CSS properties become camelCase in JavaScript, so it is element.style.backgroundColor.

How do you read a data-id attribute from an element?

  • element.data.id
  • element.getData('id')
  • element.dataset.id
  • element.attributes.id

Answer: element.dataset.id. Custom data-* attributes are accessed through the dataset property, e.g. element.dataset.id.