DOM Basics — Element Selection, Traversal & Styles

querySelector, getElementById, tagName, classList, children, parentElement, getComputedStyle vs element.style, createElement, appendChild, remove — the DOM toolkit every frontend interview assumes you know.

9 min read
JavaScript
DOM
Browser
Fundamentals

TABLE OF CONTENTS

The DOM (Document Object Model) is the browser's in-memory tree of an HTML page. For interviews, you need to know how to find elements, read their properties, traverse the tree, and understand the difference between inline styles and computed styles.


1. Finding Elements

Loading editor...

querySelector vs getElementBy*: The querySelector methods return static NodeLists. The getElementBy* methods return live HTMLCollections — they update automatically when the DOM changes.


2. Element Properties

Loading editor...


3. classList API

Loading editor...

Interview use: getElementsByClassName (#24) checks element.classList.contains(className) to match descendants.


4. Attributes

Loading editor...


5. Traversing the Tree

Loading editor...

Important: children returns only element nodes. childNodes returns ALL nodes (text nodes, comments, etc.). Always use children for tree traversal — it's what the native DOM methods traverse.

Interview use: DFS walk in getElementsByClassName (#24) — iterate element.children.


6. Creating, Inserting, and Removing Elements

Loading editor...


7. Styles

Inline Styles (element.style)

Loading editor...

Computed Styles (getComputedStyle)

Loading editor...

Key difference: element.style only reads inline styles. getComputedStyle(element) reads the final applied style after all CSS rules and inheritance are resolved.

Interview use: getElementsByStyle (#24) — use getComputedStyle to check the actual rendered style.


8. Events

Loading editor...


9. Data Storage on Elements

Loading editor...


Quick Reference

TaskMethod/Property
Find firstquerySelector(css)
Find allquerySelectorAll(css)
Tag nameelement.tagName (UPPERCASE in HTML)
Class checkelement.classList.contains(cls)
Child elementselement.children (elements only)
Parentelement.parentElement
Inline styleelement.style.property
Computed stylegetComputedStyle(element).property
Createdocument.createElement(tag)
Appendparent.appendChild(el) or parent.append(el)
Removeel.remove()

Interview Tips

  • Use element.children, not childNodeschildNodes includes text nodes and comments.
  • Tag names are UPPERCASE in HTMLelement.tagName returns 'DIV', not 'div'. Use .toUpperCase() for case-insensitive comparison.
  • getComputedStyle, not element.style — the interviewer wants to see you know the difference.
  • DFS over children preserves document order — the native DOM methods return elements in document order, which is DFS pre-order.

Related Articles


Let's Connect

© 2026 Naveen Karthik // Built with React & MUI