Skip to content
Laviyx Learn

Try

JavaScript DOM and Events Practice

Practise the JavaScript DOM: select and change elements, handle clicks, typing and forms, use event delegation, and build lists and tables. Every solution runs live in the page, so you can click and type to try it.

Intermediate10 problemsUpdated

Review first: Introduction to the DOM, Selecting Elements, Changing Content and Classes, Creating and Removing Elements, Events, Handling Forms, Bubbling and Delegation

  1. 1.Change text on click

    Beginner

    When the button is clicked, change the heading to Welcome to Laviyx Learn.

    HTML (HTML)
    <h1 id="title">Hello</h1>
    <button id="change">Change heading</button>
    Show hint

    Select both elements, then use addEventListener("click", ...) and set textContent.

    Show solution
    JavaScript
    const title = document.querySelector("#title");
    const button = document.querySelector("#change");
    
    button.addEventListener("click", () => {
      title.textContent = "Welcome to Laviyx Learn";
    });
    Try it
  2. 2.A counter

    Beginner

    Make the + and - buttons change the number by 1. The number must never go below 0.

    HTML (HTML)
    <button id="minus">-</button>
    <span id="count">0</span>
    <button id="plus">+</button>
    Show hint

    Keep the number in a variable, change it in each click handler, then write it to the page.

    Show solution
    JavaScript
    const countEl = document.querySelector("#count");
    let count = 0;
    
    function show() {
      countEl.textContent = count;
    }
    
    document.querySelector("#plus").addEventListener("click", () => {
      count++;
      show();
    });
    
    document.querySelector("#minus").addEventListener("click", () => {
      if (count > 0) count--;
      show();
    });
    Try it
  3. 3.A dark mode switch

    Beginner

    Clicking the button switches the page between light and dark by adding or removing the class dark on <body>. The button text should say Dark mode or Light mode, whichever the next click turns on.

    HTML (HTML)
    <style>
      body { padding: 12px; font-family: sans-serif; }
      body.dark { background: #1e1e1e; color: #f0f0f0; }
    </style>
    <p>Some text to read.</p>
    <button id="theme">Dark mode</button>
    Show hint

    classList.toggle("dark") adds or removes the class and returns true when it was added.

    Show solution
    JavaScript
    const button = document.querySelector("#theme");
    
    button.addEventListener("click", () => {
      const isDark = document.body.classList.toggle("dark");
      button.textContent = isDark ? "Light mode" : "Dark mode";
    });
    Try it
  4. 4.Add items to a list

    Beginner

    When the button is clicked, add the text from the input as a new list item, then clear the input. Ignore empty or blank input. Pressing Enter in the input should also add the item.

    HTML (HTML)
    <input id="item" placeholder="New item">
    <button id="add">Add</button>
    <ul id="list"></ul>
    Show hint

    document.createElement("li"), set its textContent, then append it. Use trim() to ignore blank input.

    Show solution
    JavaScript
    const input = document.querySelector("#item");
    const list = document.querySelector("#list");
    
    function addItem() {
      const text = input.value.trim();
      if (text === "") return;
      const li = document.createElement("li");
      li.textContent = text;
      list.append(li);
      input.value = "";
      input.focus();
    }
    
    document.querySelector("#add").addEventListener("click", addItem);
    input.addEventListener("keydown", (event) => {
      if (event.key === "Enter") addItem();
    });
    Try it
  5. 5.Remove items with event delegation

    Intermediate

    Each list item has a Remove button. With a single event listener on the <ul>, remove the item whose button was clicked. It must also work for items added later.

    HTML (HTML)
    <ul id="tasks">
      <li>Read a chapter <button class="remove">Remove</button></li>
      <li>Practise SQL <button class="remove">Remove</button></li>
      <li>Push to GitHub <button class="remove">Remove</button></li>
    </ul>
    Show hint

    In the listener, check event.target.matches(".remove"), then use closest("li") to find the item.

    Show solution
    JavaScript
    const tasks = document.querySelector("#tasks");
    
    tasks.addEventListener("click", (event) => {
      if (event.target.matches(".remove")) {
        event.target.closest("li").remove();
      }
    });
    Try it
  6. 6.A live character counter

    Beginner

    Show how many characters are in the text box as the user types, as 12 / 100. When more than 100 characters are typed, add the class over to the counter so it turns red.

    HTML (HTML)
    <style>
      .over { color: #c62828; font-weight: bold; }
    </style>
    <textarea id="message" rows="3" cols="40"></textarea>
    <p id="counter">0 / 100</p>
    Show hint

    The input event fires on every change. classList.toggle("over", condition) sets the class from a true or false value.

    Show solution
    JavaScript
    const message = document.querySelector("#message");
    const counter = document.querySelector("#counter");
    const limit = 100;
    
    message.addEventListener("input", () => {
      const length = message.value.length;
      counter.textContent = `${length} / ${limit}`;
      counter.classList.toggle("over", length > limit);
    });
    Try it
  7. 7.Check a form before sending

    Intermediate

    When the form is submitted, stop the page from reloading. If the name is empty or the email does not contain @, show an error message in #result. Otherwise show Thanks, <name>! and reset the form.

    HTML (HTML)
    <style>
      .error { color: #c62828; }
    </style>
    <form id="signup">
      <label>Name <input name="name"></label>
      <label>Email <input name="email"></label>
      <button>Sign up</button>
    </form>
    <p id="result"></p>
    Show hint

    event.preventDefault() stops the reload. form.elements.name.value reads a field by its name.

    Show solution
    JavaScript
    const form = document.querySelector("#signup");
    const result = document.querySelector("#result");
    
    form.addEventListener("submit", (event) => {
      event.preventDefault();
      const name = form.elements.name.value.trim();
      const email = form.elements.email.value.trim();
    
      if (name === "" || !email.includes("@")) {
        result.textContent = "Please enter your name and a valid email.";
        result.className = "error";
        return;
      }
    
      result.textContent = `Thanks, ${name}!`;
      result.className = "";
      form.reset();
    });
    Try it
  8. 8.Filter a list as you type

    Intermediate

    As the user types in the search box, show only the courses whose name contains the text, ignoring upper and lower case. Show No matches when nothing matches.

    HTML (HTML)
    <input id="search" placeholder="Search courses">
    <ul id="courses">
      <li>Python</li>
      <li>JavaScript</li>
      <li>Java</li>
      <li>SQL</li>
      <li>React</li>
    </ul>
    <p id="empty" hidden>No matches</p>
    Show hint

    Loop over the items, compare toLowerCase() versions, and set each item's hidden property.

    Show solution
    JavaScript
    const search = document.querySelector("#search");
    const items = document.querySelectorAll("#courses li");
    const empty = document.querySelector("#empty");
    
    search.addEventListener("input", () => {
      const text = search.value.trim().toLowerCase();
      let shown = 0;
    
      items.forEach((item) => {
        const match = item.textContent.toLowerCase().includes(text);
        item.hidden = !match;
        if (match) shown++;
      });
    
      empty.hidden = shown > 0;
    });
    Try it
  9. 9.Tabs

    Intermediate

    Clicking a tab button shows the panel with the matching data-tab value and hides the others. The clicked button gets the class active.

    HTML (HTML)
    <style>
      .tabs button.active { background: #1d3b4f; color: white; }
      .panel { padding: 8px 0; }
    </style>
    <div class="tabs">
      <button class="active" data-tab="html">HTML</button>
      <button data-tab="css">CSS</button>
      <button data-tab="js">JavaScript</button>
    </div>
    <div class="panel" data-panel="html">HTML gives a page its structure.</div>
    <div class="panel" data-panel="css" hidden>CSS makes it look good.</div>
    <div class="panel" data-panel="js" hidden>JavaScript makes it interactive.</div>
    Show hint

    button.dataset.tab reads data-tab. Compare it with each panel's dataset.panel.

    Show solution
    JavaScript
    const buttons = document.querySelectorAll(".tabs button");
    const panels = document.querySelectorAll(".panel");
    
    buttons.forEach((button) => {
      button.addEventListener("click", () => {
        const tab = button.dataset.tab;
        buttons.forEach((b) => b.classList.toggle("active", b === button));
        panels.forEach((panel) => {
          panel.hidden = panel.dataset.panel !== tab;
        });
      });
    });
    Try it
  10. 10.Build a table from data

    Intermediate

    Using the orders array, fill the table body with one row per order, then add a last row with the total amount. Use createElement, not innerHTML, so that the data cannot inject HTML.

    HTML (HTML)
    <style>
      table { border-collapse: collapse; }
      th, td { border: 1px solid #999; padding: 4px 10px; }
      tfoot td { font-weight: bold; }
    </style>
    <table>
      <thead><tr><th>Customer</th><th>Amount</th></tr></thead>
      <tbody id="rows"></tbody>
      <tfoot><tr><td>Total</td><td id="total"></td></tr></tfoot>
    </table>
    Show hint

    For each order, create a tr with two td cells. Add up the amounts with reduce.

    Show solution
    JavaScript
    const orders = [
      { customer: "Asha", amount: 120 },
      { customer: "Ravi", amount: 100 },
      { customer: "Meena", amount: 850 },
    ];
    
    const rows = document.querySelector("#rows");
    
    for (const order of orders) {
      const tr = document.createElement("tr");
      for (const value of [order.customer, order.amount]) {
        const td = document.createElement("td");
        td.textContent = value;
        tr.append(td);
      }
      rows.append(tr);
    }
    
    const total = orders.reduce((sum, order) => sum + order.amount, 0);
    document.querySelector("#total").textContent = total;
    Try it