DOM + EVENTS + PROJECT – JavaScript Day 2

πŸš€ DAY 2: DOM EVENTS PROJECTDOM EVENTS PROJECT

What is the DOM?

DOM (Document Object Model) = how JavaScript β€œsees” your HTML.

πŸ‘‰ It lets you:

  • Select elements
  • Change content
  • Respond to user actions

πŸ” 1. Selecting Elements

let title = document.getElementById("title");
console.log(title);

Other ways:

document.querySelector(".className");
document.querySelectorAll("p");

✏️ 2. Changing Content

document.getElementById(“title”).innerText = “New Text”;

document.getElementById("title").innerText = "New Text";

Change HTML:

element.innerHTML = "<b>Hello</b>";

🎨 3. Changing Styles

document.getElementById("title").style.color = "blue";

πŸ–±οΈ 4. Events (User Interaction)

Example: Click

button.addEventListener("click", function() {
  alert("Button clicked!");
});

⌨️ 5. Input Event

input.addEventListener("input", function() {
  console.log(input.value);
});

This is your first real-world app πŸ”₯

πŸ“¦ Features:

  • Add task
  • Display tasks
  • Delete task

πŸ’» FULL CODE

<!DOCTYPE html>
<html>
<head>
  <title>To-Do App</title>
</head>
<body>

<h2>To-Do List</h2>

<input id="taskInput" placeholder="Enter task">
<button id="addBtn">Add Task</button>

<ul id="taskList"></ul>

<script>
let input = document.getElementById("taskInput");
let button = document.getElementById("addBtn");
let list = document.getElementById("taskList");

button.addEventListener("click", function() {
  let task = input.value;

  if (task === "") return;

  let li = document.createElement("li");
  li.innerText = task;

  // Delete button
  let deleteBtn = document.createElement("button");
  deleteBtn.innerText = "Delete";

  deleteBtn.addEventListener("click", function() {
    li.remove();
  });

  li.appendChild(deleteBtn);
  list.appendChild(li);

  input.value = "";
});
</script>

</body>
</html>

🎯 YOUR TASK (VERY IMPORTANT)

Upgrade this app:

βœ… Add these features:

  1. βœ” Mark task as completed (click to strike through)
  2. βœ” Save tasks (use localStorage)
  3. βœ” Press Enter key to add task

πŸ’‘ Hints (Try yourself first!)

βœ” Strike-through:

li.style.textDecoration = "line-through";

βœ” Save to localStorage:

localStorage.setItem("tasks", JSON.stringify(array));

βœ” Get from localStorage:

JSON.parse(localStorage.getItem("tasks"));

What You Just Learned

  • DOM manipulation
  • Event handling
  • Dynamic elements
  • Real app logic

πŸ‘‰ This is core JavaScript power

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *