DOM Interview Questions
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";
elementnow holds a reference to the DOM object representingmyElement.innerTextis 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.textContentorinnerHTMLsets the element’s textual or HTML content.appendChild()(orappend()) inserts the new element into the DOM, making it visible on the page.