JavaScript DOM Basics

Select, read, and update HTML elements with JavaScript.

selectorseventsmanipulation

Table of Contents

JavaScript DOM Tutorial (Beginner -> Practical)

The DOM (Document Object Model) allows JavaScript to interact with a web page. When a browser loads HTML, it converts it into a tree-like structure of objects. JavaScript can then read, modify, add, or delete elements dynamically.

JavaScript DOM overview showing document tree, element selection, and dynamic content updates
Overview of DOM structure, element selection, and manipulation in JavaScript.

1. What is the DOM?

The DOM represents your HTML as objects.

<h2 id="title">Hello World</h2>

document.getElementById("title").innerText = "Hello World!";

2. Selecting Elements

You must first select elements before modifying them.

// By ID
let el = document.getElementById("title");

// By class
let items = document.getElementsByClassName("item");

// By tag
let tags = document.getElementsByTagName("p");

// Modern (recommended)
let el2 = document.querySelector("#title");
let all = document.querySelectorAll(".item");

3. Changing Content

let el = document.getElementById("title");

el.innerText = "New Text";
el.innerHTML = "<b>Bold Text</b>";

4. Changing Styles

el.style.color = "red";
el.style.fontSize = "30px";

5. Handling Events

JavaScript responds to user actions like clicks.

<button onclick="changeText()">Click Me</button>
<p id="text">Hello</p>

function changeText() {
    document.getElementById("text").innerText = "Changed!";
}

Better approach (separate JS):

document.getElementById("btn").addEventListener("click", function() {
    console.log("Button clicked");
});

6. Creating & Adding Elements

let newEl = document.createElement("p");
newEl.innerText = "New Paragraph";

document.body.appendChild(newEl);

7. Removing Elements

let el = document.getElementById("title");
el.remove();

8. DOM Tree Structure

HTML elements are arranged in a parent-child tree structure. Understanding this helps with selection, traversal, and updates.

9. Traversing the DOM

let parent = el.parentElement;
let child = el.children;
let first = el.firstElementChild;
let last = el.lastElementChild;

10. Real-Life Example

<input type="text" id="name">
<button onclick="showName()">Submit</button>
<p id="result"></p>

function showName() {
    let name = document.getElementById("name").value;
    document.getElementById("result").innerText = "Hello " + name;
}

11. Important Tips

  • Use querySelector for flexibility.
  • Avoid inline onclick in real projects.
  • Keep HTML, CSS, and JS separate.
  • Use event listeners for cleaner code.

12. When to Use DOM

Use DOM when you want to update content dynamically, handle user input, create interactive pages, and build forms/buttons/UI.

Simple JavaScript DOM Examples

Small, practical examples for tutorials and practice pages.

1. Change Text on Button Click

<p id="demoText">Hello</p>
<button id="demoTextBtn">Click Me</button>

<script>
document.getElementById("demoTextBtn").addEventListener("click", function () {
  document.getElementById("demoText").innerText = "Welcome!";
});
</script>

Hello

2. Show Input Value

<input type="text" id="demoName" placeholder="Enter name">
<button id="demoNameBtn">Submit</button>
<p id="demoNameResult"></p>

<script>
document.getElementById("demoNameBtn").addEventListener("click", function () {
  const name = document.getElementById("demoName").value;
  document.getElementById("demoNameResult").innerText = "Hello " + name;
});
</script>

3. Change Background Color

<button id="demoColorBtn">Change Color</button>
<div id="demoColorBox">Color Box</div>

<script>
document.getElementById("demoColorBtn").addEventListener("click", function () {
  document.getElementById("demoColorBox").style.backgroundColor = "lightblue";
});
</script>
Color Box

4. Hide / Show Element

<p id="demoPara">This is a paragraph</p>
<button id="demoToggleBtn">Hide/Show</button>

<script>
document.getElementById("demoToggleBtn").addEventListener("click", function () {
  const p = document.getElementById("demoPara");
  p.style.display = p.style.display === "none" ? "block" : "none";
});
</script>

This is a paragraph

5. Add New Element

<button id="demoAddBtn">Add Item</button>
<ul id="demoList"></ul>

<script>
document.getElementById("demoAddBtn").addEventListener("click", function () {
  const li = document.createElement("li");
  li.innerText = "New Item";
  document.getElementById("demoList").appendChild(li);
});
</script>

    6. Remove Element

    <p id="demoRemoveMe">Remove this text</p>
    <button id="demoRemoveBtn">Remove</button>
    
    <script>
    document.getElementById("demoRemoveBtn").addEventListener("click", function () {
      const el = document.getElementById("demoRemoveMe");
      if (el) el.remove();
    });
    </script>

    Remove this text

    7. Event Listener Example

    <button id="demoEventBtn">Click Me</button>
    <p id="demoEventMsg"></p>
    
    <script>
    document.getElementById("demoEventBtn").addEventListener("click", function () {
      document.getElementById("demoEventMsg").innerText = "Button clicked!";
    });
    </script>

    8. Simple Form Validation

    <input type="text" id="demoUsername" placeholder="Enter username">
    <button id="demoValidateBtn">Submit</button>
    <p id="demoMsg"></p>
    
    <script>
    document.getElementById("demoValidateBtn").addEventListener("click", function () {
      const user = document.getElementById("demoUsername").value.trim();
      document.getElementById("demoMsg").innerText = user === "" ? "Field cannot be empty" : "Success!";
    });
    </script>

    Related Topics

    Continue with Events and DOM Advanced, and revisit Objects to better understand node and event data structures.

    10 DOM Basics Interview Q&A

    1What does DOM stand for?easy
    Answer: Document Object Model.
    2Difference between getElementById and querySelector?easy
    Answer: getElementById is ID-specific and fast; querySelector uses CSS selectors.
    3How to select multiple elements?easy
    Answer: Use querySelectorAll().
    4innerHTML vs textContent?medium
    Answer: innerHTML parses HTML; textContent writes plain text.
    5How to attach click event?easy
    Answer: element.addEventListener("click", fn).
    6How to change CSS class via JS?easy
    Answer: Use classList.add/remove/toggle.
    7What is event bubbling?medium
    Answer: Event propagates from target to parent elements upward.
    8How to create new element?easy
    Answer: Use document.createElement().
    9How to remove element?easy
    Answer: Use element.remove() or parent removeChild.
    10Why prefer addEventListener over onclick?medium
    Answer: Supports multiple handlers and better separation of concerns.

    10 DOM Basics MCQs

    1

    DOM is a:

    ADatabase
    BDocument tree model
    CCSS rule
    DHTTP method
    Explanation: DOM models HTML as node tree.
    2

    Select by id method:

    AgetElementById
    BqueryAll
    CgetByClass
    DselectId
    Explanation: standard API is getElementById.
    3

    querySelectorAll returns:

    Asingle element
    BNodeList
    Cobject
    Dmap
    Explanation: it returns a NodeList of matches.
    4

    Add click event with:

    AonClick()
    BaddEventListener()
    Cevent.click()
    Dattach()
    Explanation: addEventListener is preferred modern API.
    5

    Plain text update property:

    AtextContent
    BhtmlOnly
    Cstyle
    Ddataset
    Explanation: textContent safely writes text.
    6

    classList.toggle does:

    AAlways add class
    BAdd/remove based on presence
    CRemove all classes
    DCreate element
    Explanation: toggle switches class state.
    7

    createElement creates:

    Anew DOM element node
    Bevent object
    Cstylesheet
    DAPI request
    Explanation: API returns element node object.
    8

    innerHTML should be used carefully because:

    ASlow internet
    BXSS/security risk with untrusted input
    CNo styling
    DNo events
    Explanation: avoid injecting untrusted HTML content.
    9

    Event bubbling goes:

    Aparent to child
    Btarget to ancestors
    Crandom
    Dnone
    Explanation: bubbling travels upward.
    10

    Advanced continuation page is:

    Ajs-dom-advanced.html
    Bjs-variables.html
    Cjs-switch-statement.html
    Djs-history.html
    Explanation: next DOM learning step is advanced DOM page.