Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Handle Event Propagation and Delegation | Event Handling and User Interactions in JavaScript
Advanced JavaScript Mastery

book
Challenge: Handle Event Propagation and Delegation

Task

You're building a dynamic list where users can add and delete specific items.

  1. Use event delegation by adding a single click event listener to the ul with ID dynamic-list ;

  2. When an item is clicked:

    • If the clicked element is an <li> , show an alert with the text of the clicked item;

    • If the clicked element is a "Delete" button, remove the corresponding <li> item from the list.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<ul id="dynamic-list">
<li>Item 1 <button class="delete-btn">Delete</button></li>
<li>Item 2 <button class="delete-btn">Delete</button></li>
</ul>
<button id="add-item">Add Item</button>
<script src="index.js"></script>
</body>
</html>
  • Use event.target.tagName === 'LI' to check if the clicked element is an <li> ;

  • Use event.target.classList.contains('delete-btn') to check if the clicked element is a "Delete" button.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<ul id="dynamic-list">
<li>Item 1 <button class="delete-btn">Delete</button></li>
<li>Item 2 <button class="delete-btn">Delete</button></li>
</ul>
<button id="add-item">Add Item</button>
<script src="index.js"></script>
</body>
</html>

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 3. Kapitel 5

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

We use cookies to make your experience better!
some-alt