Overview

This lab focuses on dynamically creating and manipulating HTML elements using JavaScript. You'll learn how to create elements from scratch, add them to the page, and use template literals for cleaner HTML generation. These skills are essential for building interactive web applications that respond to user actions by creating new content on the fly.

Duration: Approximately 60 minutes

Learning Objectives

By the end of this lab, students will be able to:

  • Create new HTML elements using document.createElement()
  • Set element properties: textContent, className, id
  • Add elements to the page using appendChild()
  • Remove elements using remove()
  • Use template literals with innerHTML for complex HTML
  • Handle form input and dynamically add items to lists
  • Implement delete functionality for dynamically created elements

Task 1: Interactive Todo List

📸 Reference Effect

Check out the final effect: View Task 1 Screenshot

🎯 Key Learning Points

Master creating DOM elements dynamically. Learn how to create elements, set their properties, add them to the page, and handle user interactions with dynamically created content.

Task Instructions

  1. Create the addTodo(todoText) function:
    • Step 1: Create a new li element using document.createElement('li')
    • Step 2: Add the 'todo-item' class using classList.add()
    • Step 3: Create a span element for the todo text
    • Step 4: Set the span's textContent to the todoText
    • Step 5: Create a delete button element
    • Step 6: Set the button's text to '❌ Delete'
    • Step 7: Add a click event listener to the button that calls deleteTodo()
    • Step 8: Append the span to the li element using li.appendChild(span)
    • Step 9: Append the button to the li element
    • Step 10: Get the todo list container and append the li to it
    • Step 11: Update the todo counter by calling updateTodoCount()
  2. Create the deleteTodo(event) function:
    • Step 1: Get the button that was clicked using event.target
    • Step 2: Get the parent li element using parentElement
    • Step 3: Remove the li element using li.remove()
    • Step 4: Update the todo counter
  3. Create the updateTodoCount() function:
    • Step 1: Select all todo items using querySelectorAll('.todo-item')
    • Step 2: Get the count using the length property
    • Step 3: Update the counter display element
  4. Create the handleAddTodo(event) function:
    • Step 1: Prevent form submission
    • Step 2: Get the input element and its value
    • Step 3: Trim the input value
    • Step 4: Check if the input is not empty
    • Step 5: If not empty, call addTodo() with the trimmed value
    • Step 6: Clear the input field by setting value = ''
  5. Set up event listeners:
    • Select the todo form and add submit event listener

📝 Example createElement Pattern:

function addTodo(todoText) {
  // Create the list item
  const li = document.createElement('li');
  li.classList.add('todo-item');
  
  // Create and add the text
  const span = document.createElement('span');
  span.textContent = todoText;
  
  // Append to list item
  li.appendChild(span);
  
  // Add to the page
  const todoList = document.querySelector('#todo-list');
  todoList.appendChild(li);
}

✅ Todo List Demo

Total Todos: 0

🔑 Key Concepts Used

  • createElement: document.createElement('tagName')
  • Setting Properties: textContent, className
  • Appending Elements: appendChild(element)
  • Removing Elements: element.remove()
  • Parent/Child Navigation: parentElement

Task 2: User Card Generator

📸 Reference Effect

Check out the final effect: View Task 2 Screenshot

🎯 Key Learning Points

Master template literals for creating HTML. Learn how to use innerHTML with template literals to create complex HTML structures more efficiently than createElement.

Task Instructions

  1. Create the generateCard(name, role, email) function:
    • Step 1: Create a template literal string for the card HTML
    • Step 2: Use backticks (`) for template literals
    • Step 3: Include placeholders using ${name}, ${role}, ${email}
      💡 Tip: Template literals allow you to embed variables directly in strings!
    • Step 4: The HTML should include:
      • A div with class 'user-card'
      • An h3 for the name
      • A p with class 'role' for the role
      • A p with class 'email' for the email
      • A delete button
    • Step 5: Return the HTML string
  2. Create the addCard(name, role, email) function:
    • Step 1: Get the HTML string from generateCard()
    • Step 2: Create a temporary div element
    • Step 3: Set the div's innerHTML to the HTML string
    • Step 4: Get the first child of the temp div (the card)
    • Step 5: Find the delete button in the card
    • Step 6: Add click event listener to delete button
    • Step 7: Append the card to the cards container
    • Step 8: Update the card counter
  3. Create the deleteCard(event) function:
    • Step 1: Get the button that was clicked
    • Step 2: Find the parent card element (use closest('.user-card'))
    • Step 3: Remove the card
    • Step 4: Update the counter
  4. Create the updateCardCount() function:
    • Step 1: Count all cards with class 'user-card'
    • Step 2: Update the counter display
  5. Create the handleAddCard(event) function:
    • Step 1: Prevent form submission
    • Step 2: Get values from name, role, and email inputs
    • Step 3: Trim all values
    • Step 4: Check if all fields are filled
    • Step 5: If valid, call addCard() and clear the form

📝 Example Template Literal:

function generateCard(name, role, email) {
  return `
    <div class="user-card">
      <h3>${name}</h3>
      <p class="role">${role}</p>
      <p class="email">${email}</p>
      <button class="delete-btn">Delete</button>
    </div>
  `;
}

👤 User Card Generator Demo

Total Cards: 0

🔑 Key Concepts Used

  • Template Literals: Backticks (`) for multi-line strings
  • String Interpolation: ${variable} syntax
  • innerHTML: Setting HTML content as a string
  • Element Navigation: closest() to find ancestor elements
  • Form Handling: Getting multiple input values

Questions to Answer

Please answer the following questions based on your understanding of the tasks. Write your answers in the designated areas below:

📝 Important: Write your answers directly in the HTML source code by editing the content inside the <p> tags within each answer box below.

Question 1: createElement vs innerHTML

In this lab, we used two different approaches to create HTML elements: createElement() with appendChild() (Task 1) and innerHTML with template literals (Task 2). Compare these two approaches. What are the advantages of each method? When would you choose one over the other?

Your Answer:

Type your answer here...

innerHTML can handle larger chunks of HTML
createElement method is more controllable, to add additional operations or attributes. Mostly use in user-generated content.

Question 2: Template Literals

In Task 2, we used template literals (backticks) with ${} syntax. What are template literals and why are they useful? Give an example from the lab showing how they make code easier to read compared to traditional string concatenation.

Your Answer:

Type your answer here...

template literals qouted by ` and allow multiple lines and string interpolation.
it is easier to maintain and provide cleaner code
in this case, it allow input valus as a parameter to display. like
`${name}
const nameInput = document.querySelector('#card-name');
const name = nameInput.value.trim();`

What to Submit

Upload the following files to Blackboard:

  • index.html - with answers to the questions filled in the designated answer boxes
  • script.js - with your complete JavaScript implementations (all TODO comments replaced with working code)
  • styles.css - the provided CSS file (no modifications needed)

📝 Important Notes:

  • Test adding and deleting todos - both should work smoothly
  • Test adding user cards with all three fields filled
  • Verify delete buttons work for both todos and cards
  • Check that counters update correctly when adding/removing items
  • Make sure the form clears after submitting