JavaScript DOM Manipulation


JavaScript DOM Manipulation Interview with follow-up questions

1. What is DOM in JavaScript and why is it important?

The Document Object Model (DOM) is a tree-structured, in-memory representation of an HTML (or XML) document that the browser builds from the parsed markup. Each node — element, attribute, or text — is an object, and JavaScript manipulates the page by reading and changing these objects through the document API.

const title = document.querySelector('h1');
title.textContent = 'Updated heading';

Why it matters:

  • It's the bridge between JavaScript and the page — without it, JS couldn't read or change what the user sees.
  • It enables dynamic updates: add/remove/modify elements, change styles and attributes, and respond to events — all without a full page reload.

Points interviewers often probe:

  • The DOM is an API/representation, not the raw HTML source string and not the same as the browser's internal render tree.
  • DOM operations can trigger reflow/repaint, so excessive direct manipulation hurts performance — batch changes or use DocumentFragment.
  • Frameworks like React keep a virtual DOM and diff it to minimize real DOM writes, but it all ultimately resolves to these same DOM APIs.
↑ Back to top

Follow-up 1

Can you explain the structure of the DOM?

The DOM structure is a hierarchical tree-like structure that represents the elements, attributes, and text content of an HTML or XML document. At the top of the tree is the document node, which represents the entire document. Below the document node are the element nodes, which represent HTML elements such as <div>, <p>, `

`, etc. Element nodes can have child nodes, which can be other element nodes, attribute nodes, or text nodes. Here is an example of the DOM structure for a simple HTML document: ``` My Web Page

Hello, World!

Welcome to my web page.


- Document Node
  - Element Node (html)
    - Element Node (head)
      - Element Node (title)
        - Text Node (My Web Page)
    - Element Node (body)
      - Element Node (h1)
        - Text Node (Hello, World!)
      - Element Node (p)
        - Text Node (Welcome to my web page.)</div>

Follow-up 2

How does JavaScript interact with the DOM?

JavaScript interacts with the DOM through the use of DOM methods and properties. These methods and properties allow JavaScript to access and manipulate elements, attributes, and text content in the DOM.

Here are some common ways JavaScript interacts with the DOM:

  • Accessing Elements: JavaScript can use methods like getElementById(), getElementsByClassName(), getElementsByTagName(), or querySelector() to select and retrieve elements from the DOM.

  • Modifying Elements: JavaScript can modify elements by changing their attributes, adding or removing classes, or changing their text content using properties like innerHTML or textContent.

  • Adding and Removing Elements: JavaScript can create new elements using the createElement() method and add them to the DOM using methods like appendChild() or insertBefore(). Elements can also be removed from the DOM using methods like removeChild().

  • Handling Events: JavaScript can attach event listeners to elements to respond to user interactions such as clicks, mouse movements, or form submissions. Event listeners can be added using methods like addEventListener().

  • Manipulating Styles: JavaScript can modify the style of elements by accessing and changing their CSS properties using the style property.

By using these methods and properties, JavaScript can dynamically update the content, structure, and style of a web page.

Follow-up 3

What are some common methods used for DOM manipulation?

There are several common methods used for DOM manipulation in JavaScript:

  • getElementById(): Retrieves an element from the DOM based on its unique ID.

  • getElementsByClassName(): Retrieves a collection of elements from the DOM based on their class name.

  • getElementsByTagName(): Retrieves a collection of elements from the DOM based on their tag name.

  • querySelector(): Retrieves the first element from the DOM that matches a specific CSS selector.

  • innerHTML: Gets or sets the HTML content of an element.

  • textContent: Gets or sets the text content of an element.

  • createElement(): Creates a new element.

  • appendChild(): Appends a child element to another element.

  • insertBefore(): Inserts a new element before another element.

  • removeChild(): Removes a child element from its parent element.

  • addEventListener(): Attaches an event listener to an element.

These methods, along with many others, provide powerful capabilities for manipulating the DOM in JavaScript.

2. How can you select an element in the DOM using JavaScript?

You select elements with document query methods. The modern, preferred pair takes CSS selectors:

  • querySelector(selector) — returns the first matching element (or null).
  • querySelectorAll(selector) — returns a static NodeList of all matches.
const btn = document.querySelector('.submit');        // first match
const items = document.querySelectorAll('ul#list li'); // all matches
items.forEach(li =&gt; console.log(li.textContent));

The legacy methods still exist and are slightly faster for trivial cases, but are less flexible:

  • getElementById('id') — single element by id.
  • getElementsByClassName('cls') / getElementsByTagName('tag') — return a live HTMLCollection.

Gotchas interviewers like:

  • querySelectorAll returns a static NodeList (a snapshot) and has forEach; getElementsBy* return live collections that update as the DOM changes and have no forEach (you'd spread or Array.from them).
  • querySelector returns null when nothing matches, so guard with optional chaining: document.querySelector('.x')?.focus().
  • You can scope queries to a subtree by calling them on an element, not just document: card.querySelector('.title').
↑ Back to top

Follow-up 1

What is the difference between 'getElementById', 'getElementsByClassName' and 'querySelector'?

The main difference between these methods is the way they select elements:

  • getElementById selects an element based on its unique ID attribute. It returns a single element.

  • getElementsByClassName selects elements based on their class name. It returns a collection of elements.

  • querySelector selects elements based on a CSS selector. It returns the first matching element.

Follow-up 2

Can you select multiple elements at once?

Yes, you can select multiple elements at once using the getElementsByClassName or querySelectorAll methods. These methods return a collection of elements that match the specified criteria.

Follow-up 3

What happens if the element does not exist?

If the element does not exist, the methods getElementById and querySelector will return null, while the method getElementsByClassName will return an empty collection. It's important to handle these cases in your code to avoid errors.

3. How can you modify an element's attributes in the DOM?

There are several ways to modify an element's attributes, and the best one depends on the attribute type.

Generic attributessetAttribute() / getAttribute() / removeAttribute():

const img = document.querySelector('#myImage');
img.setAttribute('src', 'new-image.jpg');
img.removeAttribute('alt');

Common properties have direct accessors, which are usually cleaner:

img.src = 'new-image.jpg';        // property reflects the attribute
input.value = 'hello';            // note: `value` property ≠ value attribute
link.href = '/home';

Classes — use classList, not string-concatenating className:

el.classList.add('active');
el.classList.toggle('open');
el.classList.remove('hidden');

Data attributes (data-*) — use the dataset API:

el.dataset.userId = '42';   // sets data-user-id="42"

Points interviewers want:

  • Prefer the property (el.value, el.checked) when you need the current state, since some attributes only reflect the initial HTML value.
  • For text, set textContent rather than innerHTMLinnerHTML parses HTML and is an XSS risk with untrusted input.
  • Use classList/dataset over manual setAttribute('class', ...) string juggling.
↑ Back to top

Follow-up 1

What methods can be used to change an element's attributes?

There are several methods that can be used to change an element's attributes in the DOM:

  1. setAttribute(): This method allows you to set or change the value of a specified attribute on an element.

  2. getAttribute(): This method allows you to get the value of a specified attribute on an element.

  3. removeAttribute(): This method allows you to remove a specified attribute from an element.

  4. hasAttribute(): This method allows you to check if an element has a specified attribute.

These methods provide flexibility in modifying an element's attributes based on your requirements.

Follow-up 2

Can you give an example of changing an element's class using JavaScript?

Yes, you can change an element's class using JavaScript. To do this, you can use the className property or the classList property.

  1. Using className property:
var element = document.getElementById('myElement');
element.className = 'newClass';

This will change the class of the element to 'newClass'.

  1. Using classList property:
var element = document.getElementById('myElement');
element.classList.add('newClass');

This will add the class 'newClass' to the element.

var element = document.getElementById('myElement');
element.classList.remove('oldClass');

This will remove the class 'oldClass' from the element.

var element = document.getElementById('myElement');
element.classList.toggle('active');

This will toggle the class 'active' on the element.

Follow-up 3

How can you add or remove classes to an element?

To add or remove classes to an element, you can use the classList property. The classList property provides methods to manipulate the classes of an element.

To add a class to an element, you can use the add() method:

var element = document.getElementById('myElement');
element.classList.add('newClass');

This will add the class 'newClass' to the element.

To remove a class from an element, you can use the remove() method:

var element = document.getElementById('myElement');
element.classList.remove('oldClass');

This will remove the class 'oldClass' from the element.

You can also toggle a class on an element using the toggle() method:

var element = document.getElementById('myElement');
element.classList.toggle('active');

This will toggle the class 'active' on the element.

4. How can you add or remove elements in the DOM?

You create elements with document.createElement() and insert/remove them with modern node methods. The current APIs are more ergonomic than the legacy appendChild/removeChild pair.

Adding:

const li = document.createElement('li');
li.textContent = 'New item';

list.append(li);              // add as last child (accepts multiple nodes/strings)
list.prepend(li);             // add as first child
existing.before(li);          // insert before a sibling
existing.after(li);           // insert after a sibling

Removing:

li.remove();                  // element removes itself — no parent reference needed

Things interviewers want noted:

  • append vs appendChild: append() can add multiple nodes and plain strings in one call and returns nothing; appendChild() takes a single node and returns it. el.remove() is far cleaner than the old el.parentNode.removeChild(el).
  • Avoid innerHTML for building structure from untrusted data — it re-parses HTML and is an XSS risk. Use createElement + textContent.
  • Batch inserts with a DocumentFragment (or build off-DOM, then append once) to avoid repeated reflows:
const frag = document.createDocumentFragment();
items.forEach(text =&gt; {
  const el = document.createElement('li');
  el.textContent = text;
  frag.append(el);
});
list.append(frag); // single DOM write
↑ Back to top

Follow-up 1

What methods can be used to add a new element?

There are several methods that can be used to add a new element to the DOM:

  • createElement(): This method creates a new element with the specified tag name.
  • appendChild(): This method appends a new element as a child of another element.
  • insertBefore(): This method inserts a new element before an existing element.
  • innerHTML: This property can be used to add HTML content to an element.

Here's an example of using the createElement() and appendChild() methods to add a new div element to the DOM:

// Create a new div element
var newDiv = document.createElement('div');

// Add some content to the div
newDiv.innerHTML = 'This is a new div element';

// Append the new div as a child of an existing element
var parentElement = document.getElementById('parent');
parentElement.appendChild(newDiv);

Follow-up 2

How can you remove an existing element?

To remove an existing element from the DOM, you can use the following methods:

  • removeChild(): This method removes a child element from its parent.
  • parentNode.removeChild(): This method removes a specific element from its parent.
  • innerHTML: This property can be used to clear the HTML content of an element.

Here's an example of using the removeChild() method to remove an element from the DOM:

// Get the element to be removed
var elementToRemove = document.getElementById('elementToRemove');

// Get the parent element
var parentElement = elementToRemove.parentNode;

// Remove the element from its parent
parentElement.removeChild(elementToRemove);

Follow-up 3

Can you give an example of adding a new element to the DOM?

Sure! Here's an example of adding a new div element to the DOM using the createElement() and appendChild() methods:

// Create a new div element
var newDiv = document.createElement('div');

// Add some content to the div
newDiv.innerHTML = 'This is a new div element';

// Append the new div as a child of an existing element
var parentElement = document.getElementById('parent');
parentElement.appendChild(newDiv);

5. What is event propagation in the context of the DOM?

Event propagation is the order in which an event travels through the DOM tree when it fires on an element. It has three phases:

  1. Capturing — the event descends from the root (document) down toward the target.
  2. Target — it reaches the element the event actually occurred on.
  3. Bubbling — it ascends back up through the ancestors to the root.

By default, addEventListener handlers run in the bubbling phase. Pass { capture: true } (or true as the third arg) to listen during capturing.

parent.addEventListener('click', () =&gt; console.log('parent'));   // bubbling
child.addEventListener('click', () =&gt; console.log('child'));
// Clicking child logs: "child" then "parent"

Points interviewers expect:

  • event.stopPropagation() halts further travel up (or down) the tree; stopImmediatePropagation() also blocks other handlers on the same element.
  • event.preventDefault() is unrelated — it cancels the browser's default action (e.g. a form submit), not propagation.
  • Event delegation leverages bubbling: attach one listener on a parent and use event.target to handle many children — efficient and works for dynamically added elements.
  • Not all events bubble (e.g. focus, blur); use their bubbling counterparts (focusin/focusout) or capture when needed.
↑ Back to top

Follow-up 1

What is the difference between event bubbling and event capturing?

Event bubbling and event capturing are two different phases of event propagation.

Event bubbling is the default behavior in which an event is first handled by the innermost element and then propagates to its parent elements. This means that the event handlers of the parent elements will also be triggered.

Event capturing, on the other hand, is the opposite behavior in which an event is first handled by the outermost element and then propagates to its child elements. This means that the event handlers of the child elements will be triggered before the event reaches the innermost element.

Follow-up 2

How can you stop event propagation?

To stop event propagation, you can use the stopPropagation() method of the event object. This method prevents the event from propagating further in the DOM tree, so the event handlers of the parent elements will not be triggered.

Here's an example:

const button = document.querySelector('button');

button.addEventListener('click', function(event) {
  event.stopPropagation();
  console.log('Button clicked');
});

const container = document.querySelector('.container');

container.addEventListener('click', function() {
  console.log('Container clicked');
});

In this example, when the button is clicked, only the event handler attached to the button will be triggered. The event will not propagate to the container element.

Follow-up 3

Can you give an example of a situation where stopping event propagation would be useful?

Stopping event propagation can be useful in situations where you want to prevent an event from triggering multiple event handlers. For example, if you have a dropdown menu that closes when you click outside of it, you can stop the click event from propagating to the document level, so that the dropdown menu does not close immediately after opening.

Here's an example:

const dropdown = document.querySelector('.dropdown');

dropdown.addEventListener('click', function(event) {
  event.stopPropagation();
  console.log('Dropdown clicked');
});

document.addEventListener('click', function() {
  console.log('Document clicked');
  // Close the dropdown menu
});

In this example, when the dropdown is clicked, only the event handler attached to the dropdown will be triggered. The event will not propagate to the document level, so the dropdown menu will not close immediately after opening.

Live mock interview

Mock interview: JavaScript DOM Manipulation

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.