DOM Interview Questions

Published: (April 28, 2026 at 01:23 AM EDT)
2 min read
Source: Dev.to

Source: Dev.to

What is DOM?

The Document Object Model (DOM) is a programming interface that represents a web page as a tree‑like structure. Each HTML element becomes an object that can be accessed and manipulated with JavaScript, allowing the page’s HTML and CSS to behave dynamically.


How to access an element using the DOM

You can retrieve elements from the document with several built‑in methods:

// Select by ID
document.getElementById("myElement");

// Select by class name (returns an HTMLCollection)
document.getElementsByClassName("myClass");

// Select by tag name (returns an HTMLCollection)
document.getElementsByTagName("p");

// Select the first matching element (CSS selector)
document.querySelector(".myClass");

// Select all matching elements (returns a NodeList)
document.querySelectorAll(".myClass");

Example: Modifying an element

const element = document.getElementById("myElement");
element.innerText = "Welcome";
  • element now holds a reference to the DOM object representing myElement.
  • innerText is a property of that object; assigning a new string updates the element’s displayed text.

What is an event in JavaScript?

Events are actions that occur in the browser—such as clicks, key presses, or page loads. JavaScript can listen for these events and execute callback functions when they happen.

// Example: listening for a click event
document.getElementById("myButton").addEventListener("click", () => {
  console.log("Button was clicked!");
});

Creating and appending a new element dynamically

JavaScript provides DOM methods to create new nodes and insert them into the document.

// 1. Create a new element (e.g., a )
const newDiv = document.createElement("div");

// 2. Add content to the element
newDiv.textContent = "I am a new div!";
// or: newDiv.innerHTML = "**Bold content**";

// 3. Append the element to a parent node
const parent = document.getElementById("container");
parent.appendChild(newDiv);
// or using the newer syntax:
// parent.append(newDiv);
  • document.createElement() creates an element node of the specified type.
  • textContent or innerHTML sets the element’s textual or HTML content.
  • appendChild() (or append()) inserts the new element into the DOM, making it visible on the page.
0 views
Back to Blog

Related posts

Read more »

DOM

What is getElementById? It is used to select a single HTML element using its unique id attribute. It returns an Element object if a match is found; otherwise,...